12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

eadlines loads a file all at once into a line-string list, while xreadlines instead loadslines on demand to avoid filling memory for large files; the last example here relies onfile iterators to achieve the equivalent of xreadlines (iterators are covered in the nextsection). The name open in all of the above can also be replaced with file as of <strong>Python</strong>2.2. See the library manual for more on the calls used here. As a general rule of thumb,the more data you read on each step, the faster your program will run.Actually, the for loop turns out to be even more generic than this—it works on anyiterable object. In fact, this is true of all iteration tools that scan objects from left toright in <strong>Python</strong>, including for loops, list comprehensions, in membership tests, andthe map built-in function.The concept of “iterable objects” is relatively new in <strong>Python</strong>. It’s essentially a generalizationof the notion of sequences—an object is considered iterable if it is either aphysically stored sequence, or an object that produces one result at a time in thecontext an iteration tool like a for loop. In a sense, iterable objects include bothphysical sequences and virtual sequences computed on demand.File IteratorsOne of the easiest ways to understand what this means is to look at how it workswith a built-in type such as the file. Recall that open file objects have a method calledreadline, which reads one line of text from a file at a time—each time we call thereadline method, we advance to the next line. At the end of the file, the empty stringis returned, which we can detect to break out of the loop:>>> f = open('script1.py')>>> f.readline( )'import sys\n'>>> f.readline( )'print sys.path\n'>>> f.readline( )'x = 2\n'>>> f.readline( )'print 2 ** 33\n'>>> f.readline( )''Today, files also have a method named next that has a nearly identical effect—itreturns the next line from a file each time it is called. The only noticeable differenceis that next raises a built-in StopIteration exception at end-of-file instead of returningan empty string:>>> f = open('script1.py')>>> f.next( )'import sys\n'260 | Chapter 13: while and for Loops

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

Saved successfully!

Ooh no, something went wrong!