在 Python 中使用 readline() 读取文件时如何检测 EOF?

How to detect EOF when reading a file with readline() in Python?

我需要使用 readline() 逐行读取文件并且无法轻易更改它。大致是:

with open(file_name, 'r') as i_file:
    while True:
        line = i_file.readline()
        # I need to check that EOF has not been reached, so that readline() really returned something

真正的逻辑比较复杂,所以我不能用readlines()一次读取文件或者写for line in i_file:.

之类的东西

有没有办法检查 readline() 是否有 EOF?它可能会抛出异常吗?

很难在互联网上找到答案,因为文档搜索重定向到一些不相关的东西(教程而不是参考,或 GNU readline),互联网上的噪音主要是关于 readlines()函数。

该解决方案应该适用于 Python 3.6+。

使用this 我建议:

fp = open("input")
while True:
     nstr = fp.readline()
     if len(nstr) == 0:
         break # or raise an exception if you want
     # do stuff using nstr

正如评论中提到的 Barmar,readline "returns EOF 处的空字符串"。

来自documentation

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.

with open(file_name, 'r') as i_file:
    while True:
        line = i_file.readline()
        if not line:
            break
        # do something with line

在 EOF 的情况下返回的空字符串计算为 False,因此这可能是海象运算符的一个很好的用例:

with open(file_name, 'r') as i_file:
    while line := i_file.readline():
        # do something with line