For example, when the with statement block exits in the following, both files’ exit
actions are automatically run to close the files, regardless of exception outcomes:
with open('data') as fin, open('results', 'w') as fout:
for line in fin:
fout.write(transform(line))
Context manager–dependent code like this seems to have become more common in
recent years, but this is likely at least in part because newcomers are accustomed to
languages that require manual close calls in all cases. In most contexts there is no need
to wrap all your Python file-processing code in with statements—the files object’s auto-
close-on-collection behavior often suffices, and manual close calls are enough for many
other scripts. You should use the with or try options outlined here only if you must
close, and only in the presence of potential exceptions. Since standard C Python auto-
matically closes files on collection, though, neither option is required in many (and
perhaps most) scripts.
Input files
Reading data from external files is just as easy as writing, but there are more methods
that let us load data in a variety of modes. Input text files are opened with either a mode
flag of r (for “read”) or no mode flag at all—it defaults to r if omitted, and it commonly
is. Once opened, we can read the lines of a text file with the readlines method:
C:\temp> python
>>> file = open('data.txt') # open input file object: 'r' default
>>> lines = file.readlines() # read into line string list
>>> for line in lines: # BUT use file line iterator! (ahead)
... print(line, end='') # lines have a '\n' at end
...
Hello file world!
Bye file world.
The readlines method loads the entire contents of the file into memory and gives it to
our scripts as a list of line strings that we can step through in a loop. In fact, there are
many ways to read an input file:
file.read()
Returns a string containing all the characters (or bytes) stored in the file
file.read(N)
Returns a string containing the next N characters (or bytes) from the file
file.readline()
Reads through the next \n and returns a line string
file.readlines()
Reads the entire file and returns a list of line strings
File Tools | 141