提问人:Serge Rogatch 提问时间:10/1/2021 更新时间:7/22/2023 访问量:7953
在 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:
有没有办法检查EOF?它可能会抛出异常吗?readline()
在互联网上很难找到答案,因为文档搜索重定向到不相关的东西(教程而不是参考资料,或GNU读行),而互联网上的噪音主要是关于功能的。readlines()
该解决方案应该在 Python 3.6+ 中工作。
答:
3赞
zabop
10/1/2021
#1
使用它,我建议:
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“在 EOF 处返回一个空字符串”。
5赞
Barmar
10/1/2021
#2
从文档中:
f.readline()
从文件中读取一行;换行符 () 保留在字符串的末尾,如果文件不以换行符结尾,则仅在文件的最后一行省略。这使得返回值明确无误;如果返回一个空字符串,则表示已到达文件的末尾,而空行由 表示,一个仅包含一个换行符的字符串。\n
f.readline()
'\n'
with open(file_name, 'r') as i_file:
while True:
line = i_file.readline()
if not line:
break
# do something with line
评论
0赞
Serge Rogatch
10/1/2021
该文档是一个教程,而不是参考,但如果它说的是你引用的内容,那么它也很好。
3赞
Jussi Nurminen
10/1/2021
#3
在 EOF 计算结果为 的情况下返回的空字符串,因此对于海象运算符来说,这可能是一个很好的用例(在 Python 3.8+ 中):False
with open(file_name, 'r') as i_file:
while line := i_file.readline():
# do something with line
评论
2赞
Serge Rogatch
10/1/2021
AFAIK,海象运算符仅在 Python 3.8+ 中可用。
0赞
Jussi Nurminen
10/1/2021
@SergeRogatch好点
评论