What value does readline return when reaching the end of the file in Python?

Viewed 20845

One can use the classic loop

file_in = open('suppliers.txt', 'r')
line = file_in.readline()

while line:
    line = file_in.readline()

to read through a file line-by-line in Python.

But what value does 'line' have when the loop exits? The Python 3 docs only read:

readline(size=-1)

Read and return one line from the stream. If size is specified, at most size bytes will be read.

The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.

Edit:

In my version of Python (3.6.1), if you open a file in binary mode, help(file_in.readline) gives

readline(size=-1, /) method of _io.BufferedReader instance

    Read and return a line from the stream.

    If size is specified, at most size bytes will be read.

    The line terminator is always b'\n' for binary files; for text
    files, the newlines argument to open can be used to select the line
    terminator(s) recognized.

which is exactly the same as the docs quoted above. But, as noted by Steve Barnes, if you open the file in text mode, you get a useful comment. (Oops! Copy-paste error on my part)

3 Answers
Related