Online Book Reader

Home Category

Learning Python - Mark Lutz [197]

By Root 1678 0

while True:

line = file.readline() # Read line by line

if not line: break

print(line, end='') # Line already has a \n

file = open('test.txt', 'rb')

while True:

chunk = file.read(10) # Read byte chunks: up to 10 bytes

if not chunk: break

print(chunk)

You typically read binary data in blocks. To read text files line by line, though, the for loop tends to be easiest to code and the quickest to run:

for line in open('test.txt').readlines():

print(line, end='')

for line in open('test.txt'): # Use iterators: best text input mode

print(line, end='')

The file readlines method loads a file all at once into a line-string list, and the last example here relies on file iterators to automatically read one line on each loop iteration (iterators are covered in detail in Chapter 14). See the library manual for more on the calls used here. The last example here is generally the best option for text files—besides its simplicity, it works for arbitrarily large files and doesn’t load the entire file into memory all at once. The iterator version may be the quickest, but I/O performance is less clear-cut in Python 3.0.

In some 2.X Python code, you may also see the name open replaced with file and the file object’s older xreadlines method used to achieve the same effect as the file’s automatic line iterator (it’s like readlines but doesn’t load the file into memory all at once). Both file and xreadlines are removed in Python 3.0, because they are redundant; you shouldn’t use them in 2.6 either, but they may pop up in older code and resources. Watch for more on reading files in Chapter 36; as we’ll see there, text and binary files have slightly different semantics in 3.0.

* * *

Loop Coding Techniques

The for loop subsumes most counter-style loops. It’s generally simpler to code and quicker to run than a while, so it’s the first tool you should reach for whenever you need to step through a sequence. But there are also situations where you will need to iterate in more specialized ways. For example, what if you need to visit every second or third item in a list, or change the list along the way? How about traversing more than one sequence in parallel, in the same for loop?

You can always code such unique iterations with a while loop and manual indexing, but Python provides two built-ins that allow you to specialize the iteration in a for:

The built-in range function produces a series of successively higher integers, which can be used as indexes in a for.

The built-in zip function returns a series of parallel-item tuples, which can be used to traverse multiple sequences in a for.

Because for loops typically run quicker than while-based counter loops, it’s to your advantage to use tools like these that allow you to use for when possible. Let’s look at each of these built-ins in turn.

Counter Loops: while and range

The range function is really a general tool that can be used in a variety of contexts. Although it’s used most often to generate indexes in a for, you can use it anywhere you need a list of integers. In Python 3.0, range is an iterator that generates items on demand, so we need to wrap it in a list call to display its results all at once (more on iterators in Chapter 14):

>>> list(range(5)), list(range(2, 5)), list(range(0, 10, 2))

([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8])

With one argument, range generates a list of integers from zero up to but not including the argument’s value. If you pass in two arguments, the first is taken as the lower bound. An optional third argument can give a step; if it is used, Python adds the step to each successive integer in the result (the step defaults to 1). Ranges can also be nonpositive and nonascending, if you want them to be:

>>> list(range(−5, 5))

[−5, −4, −3, −2, −1, 0, 1, 2, 3, 4]

>>> list(range(5, −5, −1))

[5, 4, 3, 2, 1, 0, −1, −2, −3, −4]

Although such range results may be useful all by themselves, they tend to come in most handy within for loops. For one thing, they provide a simple way to repeat an action a specific number

Return Main Page Previous Page Next Page

®Online Book Reader