Sneak Preview of Python

This is the first intend to write my first IPython Notebook.

Working with files in Python

In Python, it's not necessary to import any library to read and write files. Just use the command 'open'


In [57]:
myfilename = 'data.txt'
myfile = open(myfilename, 'r')
myfile


Out[57]:
<open file 'data.txt', mode 'r' at 0x000000000425AC90>

The second argument indicates the mode:

'r' when the file will only be read

'w' for only writing (an existing file with the same name will be erased)

'a' opens the file for appending; any data written to the file is automatically added to the end.

'r+' opens the file for both reading and writing.

So, what have we read?


In [58]:
print myfile.read()


Point x y z
1 200 100 -10
2 210 120 -8
3 220 140 -9
4 230 160 -7
5 240 180 -12

Note that the string '\n' indicates the EOL (End Of Line), aka newline character. Another useful functions are:


In [59]:
myfile = open(myfilename, 'r')
print myfile.readlines()


['Point x y z\n', '1 200 100 -10\n', '2 210 120 -8\n', '3 220 140 -9\n', '4 230 160 -7\n', '5 240 180 -12']

In [60]:
myfile = open(myfilename, 'r')
print myfile.readline()


Point x y z

We can use the pythonic iterator to read the file:


In [61]:
myfile = open(myfilename, 'r')

for line in myfile:
    print line,


Point x y z
1 200 100 -10
2 210 120 -8
3 220 140 -9
4 230 160 -7
5 240 180 -12

Now, writing a file is straight forward:


In [62]:
myoutputfile = 'output.txt'
myoutput = open(myoutputfile,'w')

myoutput.write("Time Hm0 Tp Dm\n")
myoutput.write("01-01-2020 1.5 14 270\n")
myoutput.close()

We can chech quickly what we have done:


In [63]:
check = open(myoutputfile,'r')
print check.read()


Time Hm0 Tp Dm
01-01-2020 1.5 14 270


In [63]: