Python makes it very easy to operate on files. Writing is simple:
In [21]:
f = open('blah.txt', 'w') # the returned object is of type "file"
print type(f), f
f.write("hello\n")
for i in range(1,10):
print >>f, "hello #%d"%(i)
f.close()
In [24]:
f = open('blah.txt', 'r')
print type(f), f
data = f.read()
print data, type(data)
f.close()
Note that the read() statement returns the entire content of the file. It does not matter if the file is 1 line long or MBs/GBs in size!
readlines() returns a list of all lines in the file. Simple, eh?
In [23]:
f = open('blah.txt', 'r')
i = 1
for line in f.readlines():
print "#%d: %s"%(i,line),
i+=1
f.close()
Exercise : write code that prints the frequency of each word in a file.