Skip to content

Commit be6dbfb

Browse files
authored
bpo-1613500: Don't hardcode output file mode in fileinput.FileInput (GH-12986)
1 parent 88c0937 commit be6dbfb

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

Lib/fileinput.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ def __init__(self, files=None, inplace=False, backup="", bufsize=0,
222222
warnings.warn("'U' mode is deprecated",
223223
DeprecationWarning, 2)
224224
self._mode = mode
225+
self._write_mode = mode.replace('r', 'w') if 'U' not in mode else 'w'
225226
if openhook:
226227
if inplace:
227228
raise ValueError("FileInput cannot use an opening hook in inplace mode")
@@ -348,14 +349,14 @@ def _readline(self):
348349
try:
349350
perm = os.fstat(self._file.fileno()).st_mode
350351
except OSError:
351-
self._output = open(self._filename, "w")
352+
self._output = open(self._filename, self._write_mode)
352353
else:
353354
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
354355
if hasattr(os, 'O_BINARY'):
355356
mode |= os.O_BINARY
356357

357358
fd = os.open(self._filename, mode, perm)
358-
self._output = os.fdopen(fd, "w")
359+
self._output = os.fdopen(fd, self._write_mode)
359360
try:
360361
os.chmod(self._filename, perm)
361362
except OSError:

Lib/test/test_fileinput.py

+10
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,16 @@ def test_readline_binary_mode(self):
329329
self.assertEqual(fi.readline(), b'')
330330
self.assertEqual(fi.readline(), b'')
331331

332+
def test_inplace_binary_write_mode(self):
333+
temp_file = self.writeTmp(b'Initial text.', mode='wb')
334+
with FileInput(temp_file, mode='rb', inplace=True) as fobj:
335+
line = fobj.readline()
336+
self.assertEqual(line, b'Initial text.')
337+
# print() cannot be used with files opened in binary mode.
338+
sys.stdout.write(b'New line.')
339+
with open(temp_file, 'rb') as f:
340+
self.assertEqual(f.read(), b'New line.')
341+
332342
def test_context_manager(self):
333343
t1 = self.writeTmp("A\nB\nC")
334344
t2 = self.writeTmp("D\nE\nF")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:class:`fileinput.FileInput` now uses the input file mode to correctly set
2+
the output file mode (previously it was hardcoded to ``'w'``) when
3+
``inplace=True`` is passed to its constructor.

0 commit comments

Comments
 (0)