iterating over lines in a file

Cliff Crawford cjc26 at nospam.cornell.edu
Thu Jul 20 16:03:46 EDT 2000


* Remco Gerlich <scarblac-spamtrap at pino.selwerd.nl> menulis:
| > 
| > The easiest way:
| > 
| > for line in file.readlines():
| >     block
| 
| But that would read the whole thing into memory, and he doesn't want that.
| 
| Wouldn't an xreadlines() method on file objects be cool?

readlines() has an optional argument which specifies the approximate
number of bytes to read in at a time, rather than the entire file.
So something like

for line in file.readlines(8192):
    # process line

would only use about 8k of memory.


-- 
cliff crawford    -><-    http://www.people.cornell.edu/pages/cjc26/
                          Synaesthesia now!            icq 68165166



More information about the Python-list mailing list