【问题标题】:What value does readline return when reaching the end of the file in Python?在 Python 中到达文件末尾时 readline 返回什么值?
【发布时间】:2017-12-14 14:47:38
【问题描述】:

可以使用经典循环

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

while line:
    line = file_in.readline()

在 Python 中逐行读取文件。

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

readline(size=-1)

从流中读取并返回一行。如果指定了大小,则在 大多数 size 字节将被读取。

对于二进制文件,行终止符总是 b'\n';对于文本文件, open() 的换行参数可用于选择行 已识别终止符。

编辑

在我的 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 完全相同。但是,正如Steve Barnes 所指出的,如果您以文本模式打开文件,您会得到一个有用的注释。 (糟糕!我的复制粘贴错误)

【问题讨论】:

  • 过去的文档更容易理解。
  • TextIOBase 记录 readline 在 EOF 上返回一个空字符串;以上摘自IOBase中的描述。

标签: python readline


【解决方案1】:

在 python 控制台中打开一个文件,f,然后调用它的 readline 方法的帮助会告诉你确切的信息:

>>> 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.TextIOWrapper'> 对象而不是<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 时,它将返回一个空字节数组 b'' 而不是空字符串。

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

【讨论】:

  • 查看我的编辑 -- Python 3.6.1 的文档不再以这种方式工作。
【解决方案2】:

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

f.readline() 从文件中读取一行;换行符 (\n) 留在字符串的末尾,仅在 如果文件不以换行符结尾,则文件的最后一行。这使得 返回值明确;如果f.readline() 返回一个空 字符串,已到达文件末尾,而空行是 由'\n' 表示,一个只包含一个换行符的字符串。

【讨论】:

    【解决方案3】:

    在 (Python 3) 控制台中从问题中运行代码 sn-p 表明它返回一个空字符串,如果以二进制模式打开文件,则返回一个空 Bytes 对象。

    这是否记录在某处?也许它是一种广泛的 Python 标准?

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      相关资源
      最近更新 更多