Skip to content

Commit 002665a

Browse files
rowilliaambv
authored andcommitted
bpo-30432: FileInput doesn't accept PathLike objects for file names (#1732)
* Allow FileInput to accept a single PathLike object as a parameter for `files` Fixes bpo-30432: FileInput doesn't accept PathLike objects for file names * Address comments from @ambv
1 parent d618c8c commit 002665a

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

Lib/fileinput.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,8 @@ def __init__(self, files=None, inplace=False, backup="", bufsize=0,
189189
mode="r", openhook=None):
190190
if isinstance(files, str):
191191
files = (files,)
192+
elif isinstance(files, os.PathLike):
193+
files = (os.fspath(files), )
192194
else:
193195
if files is None:
194196
files = sys.argv[1:]

Lib/test/test_fileinput.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
from io import BytesIO, StringIO
2323
from fileinput import FileInput, hook_encoded
24+
from pathlib import Path
2425

2526
from test.support import verbose, TESTFN, check_warnings
2627
from test.support import unlink as safe_unlink
@@ -530,6 +531,20 @@ def test_iteration_buffering(self):
530531
self.assertRaises(StopIteration, next, fi)
531532
self.assertEqual(src.linesread, [])
532533

534+
def test_pathlib_file(self):
535+
t1 = None
536+
try:
537+
t1 = Path(writeTmp(1, ["Pathlib file."]))
538+
with FileInput(t1) as fi:
539+
line = fi.readline()
540+
self.assertEqual(line, 'Pathlib file.')
541+
self.assertEqual(fi.lineno(), 1)
542+
self.assertEqual(fi.filelineno(), 1)
543+
self.assertEqual(fi.filename(), os.fspath(t1))
544+
finally:
545+
remove_tempfiles(t1)
546+
547+
533548
class MockFileInput:
534549
"""A class that mocks out fileinput.FileInput for use during unit tests"""
535550

0 commit comments

Comments
 (0)