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.

220 CHAPTER 10 ■ BATTERIES INCLUDED<br />

The function fileinput.filelineno returns the number of the current line within the current<br />

file. Each time you are finished with one file and begin processing the next, the file line number<br />

is reset, and restarts at 1.<br />

The function fileinput.isfirstline returns a true value if the current line is the first line<br />

of the current file—and a false value otherwise.<br />

The function fileinput.isstdin returns a true value if the current file is sys.stdin and<br />

false otherwise.<br />

The function fileinput.nextfile closes the current file and skips to the next one. The<br />

lines you skip do not count against the line count. This can be useful if you know that you are<br />

finished with the current file—for example, if each file contains words in sorted order, and you<br />

are looking for a specific word. If you have passed the word’s position in the sorted order, you<br />

can safely skip to the next file.<br />

The function fileinput.close closes the entire chain of files and finishes the iteration.<br />

Example<br />

Numbering the lines of a Python script. Let’s say you have written a Python script and you want to number the<br />

lines. Because you want the program to keep working after you’ve done this, you have to add the line numbers in<br />

comments to the right of each line. To line them up, you can use string formatting. Let’s allow each program line to<br />

get 40 characters maximum and add the comment after that. The program in Listing 10-6 shows a simple way of<br />

doing this with fileinput and the inplace parameter.<br />

Listing 10-6. Adding Line Numbers to a Python Script<br />

# numberlines.py<br />

import fileinput<br />

for line in fileinput.input(inplace=True):<br />

line = line.rstrip()<br />

num = fileinput.lineno()<br />

print '%-40s # %2i' % (line, num)<br />

If you run this program on itself, like this:<br />

$ python numberlines.py numberlines.py<br />

you end up with the program in Listing 10-7. Note that the program itself has been modified, and that if you run it<br />

like this several times, you end up with multiple numbers on each line. Recall that rstrip is a string method that<br />

returns a copy of a string, where all the whitespace on the right has been removed (see the section “String<br />

Methods” in Chapter 3 and Table B-6 in Appendix B).

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

Saved successfully!

Ooh no, something went wrong!