在 Python 中到达文件末尾时 readline return 的值是多少?

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

可以使用经典循环

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

while line:
    line = file_in.readline()

在 Python 中逐行读取文件。

但是当循环退出时'line'有什么价值呢? Python 3 文档只读:

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.

编辑:

在我的 Python (3.6.1) 版本中,如果以二进制模式打开文件,help(file_in.readline) 会给出

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.

docs quoted above. But, as noted by 完全相同,如果您以文本模式打开文件,您会得到有用的注释。 (糟糕!我的复制粘贴错误)

运行 (Python 3) 控制台中问题的代码片段显示它 returns 一个空字符串,或者如果以二进制形式打开文件则为一个空字节对象模式。

这在某处记录了吗?也许它是一种广泛的 python 标准?

来自教程:https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

在 python 控制台中打开一个文件,f,然后在它的 readline 方法上调用 help 准确地告诉你:

>>> f = open('temp.txt', 'w')
>>> help(f.readline)
Help on built-in function readline:

readline(size=-1, /) method of _io.TextIOWrapper instance
    Read until newline or EOF.

    Returns an empty string if EOF is hit immediately.

每个 readline 从当前点开始对文件的剩余部分进行操作,因此最终会遇到 EOF。

请注意,如果您以二进制模式打开文件,使用 rb 而不是 r,那么您将获得 <class '_io.BufferedReader'> 对象而不是 <class '_io.TextIOWrapper'> 对象- 那么帮助信息就不同了:

Help on built-in function readline:

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.

当此方法到达 EOF 时,它将 return 空字节数组,b'' 而不是空字符串。

请注意,以上所有内容均在 Win10 上使用 python 3.6 进行了测试。