In [1]:
outf = open('table.dat', 'w') # syntax (filename, mode), mode can be 'w' (write), 'r' (read), or 'a' (append)
outf.writelines('# index some_value another_value\n') # table header line
for i in range(20):
outf.write('{:02d} {:4d} {:3d}\n'.format(i, i**3, i+200)) # just some numbers
outf.close()
Reading from a file:
In [2]:
inf = open('table.dat', 'r')
data = []
for line in inf.readlines():
if line.find('#') > -1:
continue # catch header/comment lines
line = line.split()
data.append([float(line[0]), float(line[1]), float(line[2])])
for dat in data: # print data
print dat
inf.close()
Closing files is not immediately necessary in Python (it will not complain about it) but it reduces the possibility of confusion and is just a sign of good manners.
(see https://docs.python.org/2/library/string.html#format-specification-mini-language)
Strings come with a format
function that allows to nicely format all available data types. Some examples:
In [3]:
print '{:7.3f}'.format(235.2345345435) # float with 7 digits total, 3 decimals
print '{:5.3f}'.format(1.1) # fill up unused decimals with zeros
print '{:5.3f}'.format(1234.21321) # preserve number of decimals
print '{:+5.2f}'.format(120.23) # add sign
print '{:3d}'.format(12) # integer
print '{:03d}'.format(7) # fill up with leading zeros
print '{:10.4e}'.format(31415.9) # exponential
print '{:s}'.format('apple') # string
(see https://docs.python.org/2.7/tutorial/errors.html)
You will encounter lots of errors in your coding career and should start early to understand them. Some examples:
In [4]:
prnit 'hello'
... will cause a SyntaxError
, which means that the Python interpreter does not know what you are talking about. This is most likely due to a typo, or because you forgot something in your code. This errors occurs before the code actually starts running.
In [ ]:
if 1 < 4:
print 'one is less than four'
Indentations are critical in Python. If Python expects an indentation but you don't provide one, it will cause an IndentationError
. Note however, that no IndentationError
will occur if you intended you put something in an indented block, but you didn't. It's up to you to find things like that.
In [ ]:
def function(a, b):
return a/b
print function(1., 0)
This error message consists of two seperate things. The first line shows Traceback
, which means that the error occurs in a part of your code that is called from somewhere else. You read the error message from the top to the bottom. The first component tells you where the erroneous part of your code has been called from (in this case the print function(1., 0)
line. The second component tells you that the return
line caused the error and that it is a ZeroDivisionError
.
For a compilation of potential errors, see https://docs.python.org/2/library/exceptions.html.
Running complex code, you will run into errors during your code's runtime. The ZeroDivisionError
is a good example for this. Python provides ways to cope with these errors during runtime using so called exceptions.
In [ ]:
for i in range(10):
print 2./(i-5)
This code will eventually cause a ZeroDivisionError
. Using exceptions, the error can be caught and a different code can be run if the error occurs:
In [ ]:
for i in range(10):
try:
print 2./(i-5)
except ZeroDivisionError:
print 'not defined'
Pay attention to the indentations: you can put as many lines of code as you want in both the try
and the except
blocks. In this case, the exception will only catch ZeroDivisionError
s. If you don't know what might go wrong, you can catch all errors and ask what happened:
In [ ]:
for i in range(10):
try:
print 2./(i-5)
except Exception as e:
print 'there was an error: {:s}'.format(e)