File I/O

(see https://docs.python.org/2/tutorial/inputoutput.html)

Writing a table to a file:


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()


[0.0, 0.0, 200.0]
[1.0, 1.0, 201.0]
[2.0, 8.0, 202.0]
[3.0, 27.0, 203.0]
[4.0, 64.0, 204.0]
[5.0, 125.0, 205.0]
[6.0, 216.0, 206.0]
[7.0, 343.0, 207.0]
[8.0, 512.0, 208.0]
[9.0, 729.0, 209.0]
[10.0, 1000.0, 210.0]
[11.0, 1331.0, 211.0]
[12.0, 1728.0, 212.0]
[13.0, 2197.0, 213.0]
[14.0, 2744.0, 214.0]
[15.0, 3375.0, 215.0]
[16.0, 4096.0, 216.0]
[17.0, 4913.0, 217.0]
[18.0, 5832.0, 218.0]
[19.0, 6859.0, 219.0]

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.

String Formatting

(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


235.235
1.100
1234.213
+120.23
 12
007
3.1416e+04
apple

Python Errors and Exceptions

(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'


  File "<ipython-input-4-8aa9b26e120f>", line 1
    prnit 'hello'
                ^
SyntaxError: invalid syntax

... 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 ZeroDivisionErrors. 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)