Skip to content

Commit 56275dc

Browse files
Issue python#25510: fileinput.FileInput.readline() now returns b'' instead of ''
at the end if the FileInput was opened with binary mode. Patch by Ryosuke Ito.
2 parents 14eefe3 + 314464d commit 56275dc

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

Lib/fileinput.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,10 @@ def readline(self):
315315
return line
316316
if not self._file:
317317
if not self._files:
318-
return ""
318+
if 'b' in self._mode:
319+
return b''
320+
else:
321+
return ''
319322
self._filename = self._files[0]
320323
self._files = self._files[1:]
321324
self._filelineno = 0

Lib/test/test_fileinput.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,21 @@ def test_readline(self):
288288
with self.assertRaises(UnicodeDecodeError):
289289
# Read to the end of file.
290290
list(fi)
291+
self.assertEqual(fi.readline(), '')
292+
self.assertEqual(fi.readline(), '')
293+
294+
def test_readline_binary_mode(self):
295+
with open(TESTFN, 'wb') as f:
296+
f.write(b'A\nB\r\nC\rD')
297+
self.addCleanup(safe_unlink, TESTFN)
298+
299+
with FileInput(files=TESTFN, mode='rb') as fi:
300+
self.assertEqual(fi.readline(), b'A\n')
301+
self.assertEqual(fi.readline(), b'B\r\n')
302+
self.assertEqual(fi.readline(), b'C\rD')
303+
# Read to the end of file.
304+
self.assertEqual(fi.readline(), b'')
305+
self.assertEqual(fi.readline(), b'')
291306

292307
def test_context_manager(self):
293308
try:

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@ Core and Builtins
4848
Library
4949
-------
5050

51+
- Issue #25510: fileinput.FileInput.readline() now returns b'' instead of ''
52+
at the end if the FileInput was opened with binary mode.
53+
Patch by Ryosuke Ito.
54+
5155
- Issue #25503: Fixed inspect.getdoc() for inherited docstrings of properties.
5256
Original patch by John Mark Vandenberg.
5357

0 commit comments

Comments
 (0)