blob: 0285f03ac6e0b7cfd86e0443fbe32d9f9308cbeb [file] [log] [blame]
Fred Drake3c48ef72001-01-09 22:47:46 +00001\section{\module{xreadlines} ---
2 Efficient iteration over a file}
3
4\declaremodule{extension}{xreadlines}
5\modulesynopsis{Efficient iteration over the lines of a file.}
6
7This module defines a new object type which can efficiently iterate
8over the lines of a file. An xreadlines object is a sequence type
9which implements simple in-order indexing beginning at \code{0}, as
10required by \keyword{for} statement or the
11\function{filter()} function.
12
13Thus, the code
14
15\begin{verbatim}
16import xreadlines, sys
17
18for line in xreadlines.xreadlines(sys.stdin):
19 pass
20\end{verbatim}
21
22has approximately the same speed and memory consumption as
23
24\begin{verbatim}
25while 1:
26 lines = sys.stdin.readlines(8*1024)
27 if not lines: break
28 for line in lines:
29 pass
30\end{verbatim}
31
32except the clarity of the \keyword{for} statement is retained in the
33former case.
34
35\begin{funcdesc}{xreadlines}{fileobj}
36 Return a new xreadlines object which will iterate over the contents
37 of \var{fileobj}. \var{fileobj} must have a \method{readlines()}
38 method that supports the \var{sizehint} parameter.
39\end{funcdesc}
40
41An xreadlines object \var{s} supports the following sequence
42operation:
43
44\begin{tableii}{c|l}{code}{Operation}{Result}
45 \lineii{\var{s}[\var{i}]}{\var{i}'th line of \var{s}}
46\end{tableii}
47
48If successive values of \var{i} are not sequential starting from
49\code{0}, this code will raise \exception{RuntimeError}.
50
51After the last line of the file is read, this code will raise an
52\exception{IndexError}.