16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

266 CHAPTER 11 ■ FILES AND STUFF<br />

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

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

The New Kids on the Block: File Itera<strong>to</strong>rs<br />

It’s time for the coolest technique of all. If <strong>Python</strong> 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 <strong>Python</strong> (from version 2.2), files are iterable, which<br />

means that you can use them directly in for loops <strong>to</strong> 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 <strong>to</strong> the file. If you are willing <strong>to</strong><br />

let <strong>Python</strong> 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 <strong>to</strong> 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 S<strong>to</strong>ring 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 <strong>to</strong> 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 itera<strong>to</strong>rs in general, such as converting<br />

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

<strong>to</strong> 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!