簡體   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