Skip to content

Commit 06de1ae

Browse files
zmwangxericvsmith
authored andcommitted
bpo-31281: Fix pathlib.Path incompatibility in fileinput (gh-3208)
Fix fileinput with inplace=True to accept pathlib.Path objects.
1 parent a234485 commit 06de1ae

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)