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


<type 'file'> <open file 'blah.txt', mode 'w' at 0x1bd09c0>

In [24]:
f = open('blah.txt', 'r')
print type(f), f
data =  f.read()
print data, type(data)
f.close()


<type 'file'> <open file 'blah.txt', mode 'r' at 0x1bd0b70>
hello
hello #1
hello #2
hello #3
hello #4
hello #5
hello #6
hello #7
hello #8
hello #9
<type 'str'>

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


#1: hello
#2: hello #1
#3: hello #2
#4: hello #3
#5: hello #4
#6: hello #5
#7: hello #6
#8: hello #7
#9: hello #8
#10: hello #9

Exercise : write code that prints the frequency of each word in a file.