Page 151 -
P. 151
shredding with the for loop
Iterate through the file with the open, for,
close pattern
If you need to read from a file using Python, one way is to use the built-in
open() command. Open a file called results.txt like this:
The opened file is Put the actual name of
assigned to a file handle, result_f = open("results.txt") the file to open here.
called “result_f" here.
The call to open() creates a file handle, which is a shorthand that you’ll
use to refer to the file you are working with within your code.
Because you’ll need to read the file one line at a time, Python gives you the for
loop for just this purpose. Like while loops, the for loop runs repeatedly,
running the loop code once for each of the items in something. Think of a
for loop as your very own custom-made data shredder:
Note: unlike a real
The entire file is shredder, the for loop
fed into the for loop shredder doesn't
TM
shredder... destroy your data—it
just chops it into lines.
The for loop shredder TM
...which breaks it up into one-
line-at-a-time chunks (which are
themselves strings).
Each time the body of the for loop runs, a variable is set to a string
containing the current line of text in the file. This is referred to as iterating
through the data in the file: Open the file and give
it a file handle.
The “each_line" variable is
set to the next line from result_f = open("results.txt") Do something with the thing you've just read from
the file on each iteration.
The for loop stops when for each_line in result_f: the file. In this case, you print out the line. Notice
that the for loop's code is indented.
print(each_line)
you run out of lines to
read. result_f.close() Close the file (through the file handle)
when you're done with it.
116 Chapter 4