04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

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

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

CHAPTER 10 ■ BATTERIES INCLUDED 249<br />

■Note It is much more efficient to put the lines into a list and then join them at the end than to do something<br />

like this:<br />

# Don't do this:<br />

text = ''<br />

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

text += line<br />

Although this looks elegant, each assignment has to create a new string, which is the old string with the new<br />

one appended. This leads to a terrible waste of resources and makes your program slow. Don’t do this. If you<br />

want a more elegant way to read in all the text of a file, take a peek at Chapter 11.<br />

So, I have just created a really powerful template system in only 15 lines of code (not counting whitespace and comments).<br />

I hope you’re starting to see how powerful Python becomes when you use the standard libraries. Let’s finish this<br />

example by testing the template system. Try running it on the simple file shown in Listing 10-12.<br />

Listing 10-12. A Simple Template Example<br />

[x = 2]<br />

[y = 3]<br />

The sum of [x] and [y] is [x + y].<br />

You should see this:<br />

The sum of 2 and 3 is 5.<br />

■Note It may not be obvious, but there are three empty lines in the preceding output—two above and one<br />

below the text. Although the first two fields have been replaced by empty strings, the newlines following them<br />

are still there. Also, the print statement adds a newline, which accounts for the empty line at the end.<br />

But wait, it gets better! Because I have used fileinput, I can process several files in turn. That means that I can<br />

use one file to define values for some variables, and then another file as a template where these values are inserted.<br />

For example, I might have one file with definitions as in Listing 10-13, named magnus.txt, and a template file as<br />

in Listing 10-14, named template.txt.

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

Saved successfully!

Ooh no, something went wrong!