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