Python makes it easy to read and write files. To work with
a file, you must first open it using the built-in open() function. If you are going to read the
file, use the form “open(”, which returns a
file object. Once you have a file
object, you can use a variety of methods to perform
operations on the file.
filename)
For example, for a file object , the method F attempts to read and
return the next line from that file. If there are no lines
remaining, it returns an empty string.
F.readline()
Let's start with a small text file named trees containing just three lines:
yew oak alligator juniper
Suppose this file lives in your current directory. Here is how you might read it one line at a time:
>>> treeFile = open ( 'trees' ) >>> treeFile.readline() 'yew\n' >>> treeFile.readline() 'oak\n' >>> treeFile.readline() 'alligator juniper\n' >>> treeFile.readline() ''
Note that the newline characters ('\n')
are included in the return value. You can use the string
.rstrip() method to remove trailing
newlines, but beware: it also removes any other trailing
whitespace.
>>> 'alligator juniper\n'.rstrip() 'alligator juniper' >>> 'eat all my trailing spaces \n'.rstrip() 'eat all my trailing spaces'
To read all the lines in a file at once, use the .readlines() method. This returns a list whose
elements are strings, one per line.
>>> treeFile=open("trees")
>>> treeFile.readlines()
['yew\n', 'oak\n', 'alligator juniper\n']
A more general method for reading files is the .read() method. Used without any arguments, it
reads the entire file and returns it to you as one
string.
>>> treeFile = open ("trees")
>>> treeFile.read()
'yew\noak\nalligator juniper\n'
To read exactly characters from a file N, use the method
F. If F.read(N) characters remain in the file,
you will get them back as an N-character string. If fewer than
N characters
remain, you will get the remaining characters in the file
(if any).
N
>>> treeFile = open ( "trees" ) >>> treeFile.read(1) 'y' >>> treeFile.read(5) 'ew\noa' >>> treeFile.read(50) 'k\nalligator juniper\n' >>> treeFile.read(80) ''
One of the easiest ways to read the lines from a file is
to use a for statement. Here is an
example:
>>> >>> treeFile=open('trees')
>>> for treeLine in treeFile:
... print treeLine.rstrip()
...
yew
oak
alligator juniper
As with the .readline() method, when you
iterate over the lines of a file in this way, the lines
will contain the newline characters. If the above
example did not trim these lines with .rstrip(), each line of output would be followed
by a blank line, because the print
statement adds a newline.