GNU Info

Info Node: (python2.1-lib.info)xreadlines

(python2.1-lib.info)xreadlines


Next: calendar Prev: fileinput Up: Miscellaneous Services
Enter node , (file) or (file)node

Efficient iteration over a file
===============================

Efficient iteration over the lines of a file.

_Added in Python version 2.1_

This module defines a new object type which can efficiently iterate
over the lines of a file.  An xreadlines object is a sequence type
which implements simple in-order indexing beginning at `0', as required
by `for' statement or the `filter()' function.

Thus, the code

     import xreadlines, sys
     
     for line in xreadlines.xreadlines(sys.stdin):
         pass

has approximately the same speed and memory consumption as

     while 1:
         lines = sys.stdin.readlines(8*1024)
         if not lines: break
         for line in lines:
             pass

except the clarity of the `for' statement is retained in the former
case.

`xreadlines(fileobj)'
     Return a new xreadlines object which will iterate over the contents
     of FILEOBJ.  FILEOBJ must have a `readlines()' method that
     supports the SIZEHINT parameter.

An xreadlines object S supports the following sequence operation:

Operation                            Result
------                               -----
S[I]                                 I'th line of S

If successive values of I are not sequential starting from `0', this
code will raise `RuntimeError'.

After the last line of the file is read, this code will raise an
`IndexError'.


automatically generated by info2www version 1.2.2.9