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

Ser*_*tch 5 python exception file readline eof

我需要逐行读取文件,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
Run Code Online (Sandbox Code Playgroud)

真正的逻辑涉及更多,所以我无法立即读取文件readlines()或编写类似for line in i_file:.

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

在互联网上找到答案非常困难,因为文档搜索重定向到一些不相关的内容(教程而不是参考资料或 GNU 阅读线),而且互联网上的噪音主要与功能有关readlines()

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

Bar*_*mar 5

文档中:

\n
\n

f.readline()从文件中读取一行;换行符 ( \\n) 保留在字符串末尾,并且仅当文件\xe2\x80\x99t 以换行符结尾时才会在文件的最后一行被省略。这使得返回值明确;如果f.readline()返回一个空字符串,则已到达文件末尾,而空行由 表示\'\\n\',该字符串仅包含一个换行符。

\n
\n
with open(file_name, \'r\') as i_file:\n    while True:\n        line = i_file.readline()\n        if not line:\n            break\n        # do something with line\n
Run Code Online (Sandbox Code Playgroud)\n