blob: 7055f32ab0c8a91761e6822fc1f04361b2e3bda0 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`fileinput` --- Iterate over lines from multiple input streams
2===================================================================
3
4.. module:: fileinput
5 :synopsis: Loop over standard input or a list of files.
6.. moduleauthor:: Guido van Rossum <guido@python.org>
7.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8
9
Thomas Wouters1b7f8912007-09-19 03:06:30 +000010This module implements a helper class and functions to quickly write a
11loop over standard input or a list of files. If you just want to read or
12write one file see :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +000013
14The typical use is::
15
16 import fileinput
17 for line in fileinput.input():
18 process(line)
19
20This iterates over the lines of all files listed in ``sys.argv[1:]``, defaulting
21to ``sys.stdin`` if the list is empty. If a filename is ``'-'``, it is also
22replaced by ``sys.stdin``. To specify an alternative list of filenames, pass it
Georg Brandl96593ed2007-09-07 14:15:41 +000023as the first argument to :func:`.input`. A single file name is also allowed.
Georg Brandl116aa622007-08-15 14:28:22 +000024
25All files are opened in text mode by default, but you can override this by
Georg Brandl96593ed2007-09-07 14:15:41 +000026specifying the *mode* parameter in the call to :func:`.input` or
Georg Brandl6cb7b652010-07-31 20:08:15 +000027:class:`FileInput`. If an I/O error occurs during opening or reading a file,
Georg Brandl116aa622007-08-15 14:28:22 +000028:exc:`IOError` is raised.
29
30If ``sys.stdin`` is used more than once, the second and further use will return
31no lines, except perhaps for interactive use, or if it has been explicitly reset
32(e.g. using ``sys.stdin.seek(0)``).
33
34Empty files are opened and immediately closed; the only time their presence in
35the list of filenames is noticeable at all is when the last file opened is
36empty.
37
38Lines are returned with any newlines intact, which means that the last line in
39a file may not have one.
40
41You can control how files are opened by providing an opening hook via the
42*openhook* parameter to :func:`fileinput.input` or :class:`FileInput()`. The
43hook must be a function that takes two arguments, *filename* and *mode*, and
44returns an accordingly opened file-like object. Two useful hooks are already
45provided by this module.
46
47The following function is the primary interface of this module:
48
49
Georg Brandl71515ca2009-05-17 12:29:12 +000050.. function:: input(files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)
Georg Brandl116aa622007-08-15 14:28:22 +000051
52 Create an instance of the :class:`FileInput` class. The instance will be used
53 as global state for the functions of this module, and is also returned to use
54 during iteration. The parameters to this function will be passed along to the
55 constructor of the :class:`FileInput` class.
56
Georg Brandl6cb7b652010-07-31 20:08:15 +000057 The :class:`FileInput` instance can be used as a context manager in the
58 :keyword:`with` statement. In this example, *input* is closed after the
59 :keyword:`with` statement is exited, even if an exception occurs::
60
Raymond Hettinger7fefaff2010-09-05 23:50:32 +000061 with fileinput.input(files=('spam.txt', 'eggs.txt')) as f:
62 for line in f:
63 process(line)
Georg Brandl6cb7b652010-07-31 20:08:15 +000064
65 .. versionchanged:: 3.2
66 Can be used as a context manager.
67
Georg Brandl116aa622007-08-15 14:28:22 +000068
69The following functions use the global state created by :func:`fileinput.input`;
70if there is no active state, :exc:`RuntimeError` is raised.
71
72
73.. function:: filename()
74
75 Return the name of the file currently being read. Before the first line has
76 been read, returns ``None``.
77
78
79.. function:: fileno()
80
81 Return the integer "file descriptor" for the current file. When no file is
82 opened (before the first line and between files), returns ``-1``.
83
Georg Brandl116aa622007-08-15 14:28:22 +000084
85.. function:: lineno()
86
87 Return the cumulative line number of the line that has just been read. Before
88 the first line has been read, returns ``0``. After the last line of the last
89 file has been read, returns the line number of that line.
90
91
92.. function:: filelineno()
93
94 Return the line number in the current file. Before the first line has been
95 read, returns ``0``. After the last line of the last file has been read,
96 returns the line number of that line within the file.
97
98
99.. function:: isfirstline()
100
101 Returns true if the line just read is the first line of its file, otherwise
102 returns false.
103
104
105.. function:: isstdin()
106
107 Returns true if the last line was read from ``sys.stdin``, otherwise returns
108 false.
109
110
111.. function:: nextfile()
112
113 Close the current file so that the next iteration will read the first line from
114 the next file (if any); lines not read from the file will not count towards the
115 cumulative line count. The filename is not changed until after the first line
116 of the next file has been read. Before the first line has been read, this
117 function has no effect; it cannot be used to skip the first file. After the
118 last line of the last file has been read, this function has no effect.
119
120
121.. function:: close()
122
123 Close the sequence.
124
125The class which implements the sequence behavior provided by the module is
126available for subclassing as well:
127
128
Georg Brandl71515ca2009-05-17 12:29:12 +0000129.. class:: FileInput(files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 Class :class:`FileInput` is the implementation; its methods :meth:`filename`,
132 :meth:`fileno`, :meth:`lineno`, :meth:`filelineno`, :meth:`isfirstline`,
133 :meth:`isstdin`, :meth:`nextfile` and :meth:`close` correspond to the functions
134 of the same name in the module. In addition it has a :meth:`readline` method
135 which returns the next input line, and a :meth:`__getitem__` method which
136 implements the sequence behavior. The sequence must be accessed in strictly
137 sequential order; random access and :meth:`readline` cannot be mixed.
138
139 With *mode* you can specify which file mode will be passed to :func:`open`. It
140 must be one of ``'r'``, ``'rU'``, ``'U'`` and ``'rb'``.
141
142 The *openhook*, when given, must be a function that takes two arguments,
143 *filename* and *mode*, and returns an accordingly opened file-like object. You
144 cannot use *inplace* and *openhook* together.
145
Georg Brandl6cb7b652010-07-31 20:08:15 +0000146 A :class:`FileInput` instance can be used as a context manager in the
147 :keyword:`with` statement. In this example, *input* is closed after the
148 :keyword:`with` statement is exited, even if an exception occurs::
Georg Brandl116aa622007-08-15 14:28:22 +0000149
Georg Brandl6cb7b652010-07-31 20:08:15 +0000150 with FileInput(files=('spam.txt', 'eggs.txt')) as input:
151 process(input)
152
153 .. versionchanged:: 3.2
154 Can be used as a context manager.
155
156
157**Optional in-place filtering:** if the keyword argument ``inplace=True`` is
158passed to :func:`fileinput.input` or to the :class:`FileInput` constructor, the
159file is moved to a backup file and standard output is directed to the input file
160(if a file of the same name as the backup file already exists, it will be
161replaced silently). This makes it possible to write a filter that rewrites its
162input file in place. If the *backup* parameter is given (typically as
Georg Brandl116aa622007-08-15 14:28:22 +0000163``backup='.<some extension>'``), it specifies the extension for the backup file,
164and the backup file remains around; by default, the extension is ``'.bak'`` and
165it is deleted when the output file is closed. In-place filtering is disabled
166when standard input is read.
167
Georg Brandle720c0a2009-04-27 16:20:50 +0000168.. note::
Georg Brandl48310cd2009-01-03 21:18:54 +0000169
Guido van Rossumda27fd22007-08-17 00:24:54 +0000170 The current implementation does not work for MS-DOS 8+3 filesystems.
171
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173The two following opening hooks are provided by this module:
174
Georg Brandl116aa622007-08-15 14:28:22 +0000175.. function:: hook_compressed(filename, mode)
176
177 Transparently opens files compressed with gzip and bzip2 (recognized by the
178 extensions ``'.gz'`` and ``'.bz2'``) using the :mod:`gzip` and :mod:`bz2`
179 modules. If the filename extension is not ``'.gz'`` or ``'.bz2'``, the file is
180 opened normally (ie, using :func:`open` without any decompression).
181
182 Usage example: ``fi = fileinput.FileInput(openhook=fileinput.hook_compressed)``
183
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185.. function:: hook_encoded(encoding)
186
187 Returns a hook which opens each file with :func:`codecs.open`, using the given
188 *encoding* to read the file.
189
190 Usage example: ``fi =
191 fileinput.FileInput(openhook=fileinput.hook_encoded("iso-8859-1"))``