无法捕获python EOFError

rem*_*emy 1 python

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

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

输出是:

Line: ['nice\n']
Line: []
Line: []
Line: []
Line: []
Run Code Online (Sandbox Code Playgroud)

Kim*_*ais 6

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

您可能打算使用file.readline()- 但即使这样也不会引发错误,因此您必须执行其他操作,例如检查if not line.endswith("\n"): breaklen(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
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要删除额外的换行符,请将print语句更改为:

print("Line: %s" % line.rstrip("\n"))
Run Code Online (Sandbox Code Playgroud)