Python: Reading Files

This is how you open and read files in Python:

#lines.txt has the following three lines (without #)
#this is line 1
#this is line 2
#this is line 3
 
# Echo the contents of a file
f = open('lines.txt', 'rU')
for line in f:   ## iterates over the lines of the file
  print line,    ## trailing , so print does not add an end-of-line char
                 ## since 'line' already includes the end-of line.
f.close()
 
#output is the text in lines.txt

The second parameter in open method is the mode. We can open a file using following modes:

A) Read (r) – for reading from the file
B) Write (w) – for writing to the file
C) Append (a) – for appending text to the file
D) Universal (rU) – for reading (but being smart about different line endings, so they all convert to \n )

Leave a comment