繁体   English   中英

跳过文件的第一行时出错

[英]Error with skipping the first line of a file

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

错误示例:

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

只需使用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())

你可以用 try except 块来包装它:

try:
    next(a_file)
except StopIteration:
    # handle the exception

您可以简单地使用 python 中的try - except块来检测调用next()方法时是否发生任何错误。 如果发生任何错误,在您的情况下将是StopIteration ,我们将执行 except 块,因此程序可以顺利继续。


a_file = open("helloo.txt") 

try:
    next(a_file) 
except StopIteration:
    print("File is empty.")
    
print(a_file.read())

检查文件是否为空,如果不是,请执行next()

import os

a_file = open("helloo.txt")
if os.stat("helloo.txt").st_size != 0:
    next(a_file) 
print(a_file.read())
a_file.close()

或者你可以使用try except这样:

a_file = open("helloo.txt") 
try:
    next(a_file)
except StopIteration:
    pass

print(a_file.read())

通过=运算符将open调用分配给变量是一种不好的做法。 相反,使用with

with open("usernames.txt") as a_file:
    try:
        next(a_file)
        print(a_file.read())
    except StopIteration:
        print("Empty")

我还想向您介绍finally语句; 它仅在tryexcept都在块中使用之后出现:

with open("usernames.txt") as a_file:
    try:
        next(a_file)
        print(a_file.read())
    except StopIteration:
        print("Empty")
    finally:
        print("End!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM