warnings.warn("'U' mode is deprecated",
DeprecationWarning, 2)
self._mode = mode
+ self._write_mode = mode.replace('r', 'w') if 'U' not in mode else 'w'
if openhook:
if inplace:
raise ValueError("FileInput cannot use an opening hook in inplace mode")
try:
perm = os.fstat(self._file.fileno()).st_mode
except OSError:
- self._output = open(self._filename, "w")
+ self._output = open(self._filename, self._write_mode)
else:
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
if hasattr(os, 'O_BINARY'):
mode |= os.O_BINARY
fd = os.open(self._filename, mode, perm)
- self._output = os.fdopen(fd, "w")
+ self._output = os.fdopen(fd, self._write_mode)
try:
os.chmod(self._filename, perm)
except OSError:
self.assertEqual(fi.readline(), b'')
self.assertEqual(fi.readline(), b'')
+ def test_inplace_binary_write_mode(self):
+ temp_file = self.writeTmp(b'Initial text.', mode='wb')
+ with FileInput(temp_file, mode='rb', inplace=True) as fobj:
+ line = fobj.readline()
+ self.assertEqual(line, b'Initial text.')
+ # print() cannot be used with files opened in binary mode.
+ sys.stdout.write(b'New line.')
+ with open(temp_file, 'rb') as f:
+ self.assertEqual(f.read(), b'New line.')
+
def test_context_manager(self):
t1 = self.writeTmp("A\nB\nC")
t2 = self.writeTmp("D\nE\nF")
--- /dev/null
+:class:`fileinput.FileInput` now uses the input file mode to correctly set
+the output file mode (previously it was hardcoded to ``'w'``) when
+``inplace=True`` is passed to its constructor.