This is the first intend to write my first IPython Notebook.
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]:
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()
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()
In [60]:
myfile = open(myfilename, 'r')
print myfile.readline()
We can use the pythonic iterator to read the file:
In [61]:
myfile = open(myfilename, 'r')
for line in myfile:
print line,
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()
In [63]: