Skip to content

Commit 590e228

Browse files
committed
bpo-31281: Fix pathlib.Path incompatibility in fileinput
fileinput otherwise works fine with pathlib.Path filenames, but when inplace is set to True, the Path object needs to be converted to a str first, or appending a str suffix with + would fail.
1 parent a5b4ea1 commit 590e228

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Lib/fileinput.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ def _readline(self):
330330
else:
331331
if self._inplace:
332332
self._backupfilename = (
333-
self._filename + (self._backup or ".bak"))
333+
os.fspath(self._filename) + (self._backup or ".bak"))
334334
try:
335335
os.unlink(self._backupfilename)
336336
except OSError:

Lib/test/test_fileinput.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,19 @@ def test_pathlib_file(self):
544544
finally:
545545
remove_tempfiles(t1)
546546

547+
def test_pathlib_file_inplace(self):
548+
t1 = None
549+
try:
550+
t1 = Path(writeTmp(1, ['Pathlib file.']))
551+
with FileInput(t1, inplace=True) as fi:
552+
line = fi.readline()
553+
self.assertEqual(line, 'Pathlib file.')
554+
print('Modified %s' % line)
555+
with open(t1) as f:
556+
self.assertEqual(f.read(), 'Modified Pathlib file.\n')
557+
finally:
558+
remove_tempfiles(t1)
559+
547560

548561
class MockFileInput:
549562
"""A class that mocks out fileinput.FileInput for use during unit tests"""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix ``fileinput.FileInput(files, inplace=True)`` when ``files`` contain
2+
``pathlib.Path`` objects.

0 commit comments

Comments
 (0)