Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c029f87

Browse files
committed
Patch #1212287: fileinput.input() now has a mode parameter for
specifying the file mode input files should be opened with.
1 parent 67e9fb9 commit c029f87

4 files changed

Lines changed: 51 additions & 15 deletions

File tree

Doc/lib/libfileinput.tex

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,10 @@ \section{\module{fileinput} ---
2626
it as the first argument to \function{input()}. A single file name is
2727
also allowed.
2828

29-
All files are opened in text mode. If an I/O error occurs during
30-
opening or reading a file, \exception{IOError} is raised.
29+
All files are opened in text mode by default, but you can override this by
30+
specifying the \var{mode} parameter in the call to \function{input()}
31+
or \class{FileInput()}. If an I/O error occurs during opening or reading
32+
a file, \exception{IOError} is raised.
3133

3234
If \code{sys.stdin} is used more than once, the second and further use
3335
will return no lines, except perhaps for interactive use, or if it has
@@ -44,12 +46,14 @@ \section{\module{fileinput} ---
4446
The following function is the primary interface of this module:
4547

4648
\begin{funcdesc}{input}{\optional{files\optional{,
47-
inplace\optional{, backup}}}}
49+
inplace\optional{, backup\optional{, mode}}}}}
4850
Create an instance of the \class{FileInput} class. The instance
4951
will be used as global state for the functions of this module, and
5052
is also returned to use during iteration. The parameters to this
5153
function will be passed along to the constructor of the
5254
\class{FileInput} class.
55+
56+
\versionchanged[Added the \var{mode} parameter]{2.5}
5357
\end{funcdesc}
5458

5559

@@ -111,7 +115,7 @@ \section{\module{fileinput} ---
111115
module is available for subclassing as well:
112116

113117
\begin{classdesc}{FileInput}{\optional{files\optional{,
114-
inplace\optional{, backup}}}}
118+
inplace\optional{, backup\optional{, mode}}}}}
115119
Class \class{FileInput} is the implementation; its methods
116120
\method{filename()}, \method{fileno()}, \method{lineno()},
117121
\method{fileline()}, \method{isfirstline()}, \method{isstdin()},
@@ -122,6 +126,12 @@ \section{\module{fileinput} ---
122126
which implements the sequence behavior. The sequence must be
123127
accessed in strictly sequential order; random access and
124128
\method{readline()} cannot be mixed.
129+
130+
With \var{mode} you can specify which file mode will be passed to
131+
\function{open()}. It must be one of \code{'r'}, \code{'rU'},
132+
\code{'U'} and \code{'rb'}.
133+
134+
\versionchanged[Added the \var{mode} parameter]{2.5}
125135
\end{classdesc}
126136

127137
\strong{Optional in-place filtering:} if the keyword argument

Lib/fileinput.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,10 @@
2828
read, filename() and the line number functions return the values
2929
pertaining to the last line read; nextfile() has no effect.
3030
31-
All files are opened in text mode. If an I/O error occurs during
32-
opening or reading a file, the IOError exception is raised.
31+
All files are opened in text mode by default, you can override this by
32+
setting the mode parameter to input() or FileInput.__init__().
33+
If an I/O error occurs during opening or reading a file, the IOError
34+
exception is raised.
3335
3436
If sys.stdin is used more than once, the second and further use will
3537
return no lines, except perhaps for interactive use, or if it has been
@@ -72,7 +74,6 @@
7274
XXX Possible additions:
7375
7476
- optional getopt argument processing
75-
- specify open mode ('r' or 'rb')
7677
- isatty()
7778
- read(), read(size), even readlines()
7879
@@ -87,8 +88,8 @@
8788

8889
DEFAULT_BUFSIZE = 8*1024
8990

90-
def input(files=None, inplace=0, backup="", bufsize=0):
91-
"""input([files[, inplace[, backup]]])
91+
def input(files=None, inplace=0, backup="", bufsize=0, mode="r"):
92+
"""input([files[, inplace[, backup[, mode]]]])
9293
9394
Create an instance of the FileInput class. The instance will be used
9495
as global state for the functions of this module, and is also returned
@@ -98,7 +99,7 @@ def input(files=None, inplace=0, backup="", bufsize=0):
9899
global _state
99100
if _state and _state._file:
100101
raise RuntimeError, "input() already active"
101-
_state = FileInput(files, inplace, backup, bufsize)
102+
_state = FileInput(files, inplace, backup, bufsize, mode)
102103
return _state
103104

104105
def close():
@@ -180,7 +181,7 @@ def isstdin():
180181
return _state.isstdin()
181182

182183
class FileInput:
183-
"""class FileInput([files[, inplace[, backup]]])
184+
"""class FileInput([files[, inplace[, backup[, mode]]]])
184185
185186
Class FileInput is the implementation of the module; its methods
186187
filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
@@ -192,7 +193,7 @@ class FileInput:
192193
sequential order; random access and readline() cannot be mixed.
193194
"""
194195

195-
def __init__(self, files=None, inplace=0, backup="", bufsize=0):
196+
def __init__(self, files=None, inplace=0, backup="", bufsize=0, mode="r"):
196197
if isinstance(files, basestring):
197198
files = (files,)
198199
else:
@@ -216,6 +217,11 @@ def __init__(self, files=None, inplace=0, backup="", bufsize=0):
216217
self._backupfilename = None
217218
self._buffer = []
218219
self._bufindex = 0
220+
# restrict mode argument to reading modes
221+
if mode not in ('r', 'rU', 'U', 'rb'):
222+
raise ValueError("FileInput opening mode must be one of "
223+
"'r', 'rU', 'U' and 'rb'")
224+
self._mode = mode
219225

220226
def __del__(self):
221227
self.close()
@@ -307,7 +313,7 @@ def readline(self):
307313
except os.error: pass
308314
# The next few lines may raise IOError
309315
os.rename(self._filename, self._backupfilename)
310-
self._file = open(self._backupfilename, "r")
316+
self._file = open(self._backupfilename, self._mode)
311317
try:
312318
perm = os.fstat(self._file.fileno()).st_mode
313319
except OSError:
@@ -326,7 +332,7 @@ def readline(self):
326332
sys.stdout = self._output
327333
else:
328334
# This may raise IOError
329-
self._file = open(self._filename, "r")
335+
self._file = open(self._filename, self._mode)
330336
self._buffer = self._file.readlines(self._bufsize)
331337
self._bufindex = 0
332338
if not self._buffer:

Lib/test/test_fileinput.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Nick Mathewson
44
'''
55

6-
from test.test_support import verify, verbose, TESTFN
6+
from test.test_support import verify, verbose, TESTFN, TestFailed
77
import sys, os, re
88
from StringIO import StringIO
99
from fileinput import FileInput
@@ -183,3 +183,20 @@ def writeFiles():
183183
verify(fi.fileno() == -1)
184184
finally:
185185
remove_tempfiles(t1, t2)
186+
187+
if verbose:
188+
print "17. Specify opening mode"
189+
try:
190+
# invalid mode, should raise ValueError
191+
fi = FileInput(mode="w")
192+
raise TestFailed("FileInput should reject invalid mode argument")
193+
except ValueError:
194+
pass
195+
try:
196+
# try opening in universal newline mode
197+
t1 = writeTmp(1, ["A\nB\r\nC\rD"])
198+
fi = FileInput(files=t1, mode="U")
199+
lines = list(fi)
200+
verify(lines == ["A\n", "B\n", "C\n", "D"])
201+
finally:
202+
remove_tempfiles(t1)

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,9 @@ Extension Modules
366366
Library
367367
-------
368368

369+
- Patch #1212287: fileinput.input() now has a mode parameter for
370+
specifying the file mode input files should be opened with.
371+
369372
- Patch #1215184: fileinput now has a fileno() function for getting the
370373
current file number.
371374

0 commit comments

Comments
 (0)