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