Skip to main content
 首页 » 编程设计

python之无法捕获 python EOFError

2025年05月04日10lidabo

我读取了一个只包含一行的文件。但是,在循环结束之前我无法停止读取文件。即 python 不会抛出 EOFError 异常。我的代码有什么问题吗?

for x in range(5): 
  try: 
    line = file.readlines() 
  except EOFError: 
    break 
  print "Line:",line 

输出是:

Line: ['nice\n'] 
Line: [] 
Line: [] 
Line: [] 
Line: [] 

请您参考如下方法:

readlines()读取整个文档并返回行列表,而不仅仅是一行。

您可能打算使用 file.readline() - 但即使这样也不会引发错误,所以你必须做其他事情,比如检查 if not line.endswith("\n"): break或 len(line) < 1检测 EOF。

我个人会编写类似的功能:

with open("filename") as f: 
    for i, line in enumerate(f): 
        print("Line: %s" % line) 
        if i > 5 or not line: 
            break 

或者如果你想去掉多余的换行符,把打印语句改成:

print("Line: %s" % line.rstrip("\n"))