04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

266 CHAPTER 11 ■ FILES AND STUFF<br />

object. Note that xreadlines is somewhat “old-fashioned,” and you should instead use file iterators<br />

(explained next) in your own code.<br />

The New Kids on the Block: File Iterators<br />

It’s time for the coolest technique of all. If Python had had this since the beginning, I suspect<br />

that several of the other methods (at least xreadlines) would never have appeared. So what is<br />

this cool technique? In recent versions of Python (from version 2.2), files are iterable, which<br />

means that you can use them directly in for loops to iterate over their lines. See Listing 11-12<br />

for an example. Pretty elegant, isn’t it?<br />

Listing 11-12. Iterating Over a File<br />

f = open(filename)<br />

for line in f:<br />

process(line)<br />

In these iteration examples, I’ve been pretty casual about closing my files. Although I probably<br />

should have closed them, it’s not critical, as long as I don’t write to the file. If you are willing to<br />

let Python take care of the closing (as I have done so far), you could simplify the example even<br />

further, as shown in Listing 11-13. Here I don’t assign the opened file to a variable (like the<br />

variable f I’ve used in the other examples), and therefore I have no way of explicitly closing it.<br />

Listing 11-13. Iterating Over a File Without Storing the File Object in a Variable<br />

for line in open(filename):<br />

process(line)<br />

Note that sys.stdin is iterable, just like other files, so if you want to iterate over all the lines<br />

in standard input, you can use<br />

import sys<br />

for line in sys.stdin:<br />

process(line)<br />

Also, you can do all the things you can do with iterators in general, such as converting<br />

them into lists of strings (by using list(open(filename))), which would simply be equivalent<br />

to using readlines.<br />

Consider the following example:<br />

>>> f = open('somefile.txt', 'w')<br />

>>> print >> f, 'This is the first line'<br />

>>> print >> f, 'This is the second line'<br />

>>> print >> f, 'This is the third line'<br />

>>> f.close()<br />

>>> first, second, third = open('somefile.txt')<br />

>>> first<br />

'This is the first line\n'<br />

>>> second<br />

'This is the second line\n'

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!