首页 > 解决方案 > 跳过文件的第一行时出错

问题描述

使用该命令next(a_file),我可以跳过文件的第一行,但前提是实际上有一行。如果在命令执行时文件中没有任何内容,我会收到错误消息。我怎样才能避免这个问题?

错误示例:

a_file = open("helloo.txt") 
next(a_file) 
print(a_file.read())

标签: python

解决方案


只需使用一个try: except块。您只想捕获StopIteration异常,这样任何其他 ( FileNotFoundError,...) 都不会在这里被捕获:

a_file = open("helloo.txt") 
try:
    next(a_file)
except StopIteration:
    print("Empty file")
    # or just
    #pass

print(a_file.read())

推荐阅读