簡體   English   中英

如何添加 try & except 構造,以便腳本忽略沒有文件

[英]How to add a try & except construct so that the script ignores that there is no file

Python這門語言我不是很懂,求高手幫忙。 我有一個簡單的腳本,我需要向它添加一個結構

try:
except:

這是必要的,以便腳本忽略沒有'file.txt'文件並且不顯示錯誤。

如果文件"file.txt"丟失,script.py 腳本會顯示以下錯誤

Version 1.2.1.
Traceback (most recent call last):
  File "script.py", line 10, in <module>
    with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

我怎樣才能讓腳本忽略沒有'file.txt'並且不拋出這個errorTraceback(最近的調用最后)?

腳本代碼:

import sys

if __name__ == '__main__':
    if '-v' in sys.argv:
        print(f'Version 1.2.1.')


h = format(0x101101, 'x')[2:]

with open("file.txt") as myfile, open("save.txt", 'a') as save_file:

    for line in myfile:
        if h in line:
            save_file.write("Number = " + line + "")
            print("Number = " + line + "")

幫助如何向它添加一個try & except構造? 在此先感謝您的幫助!

try:except:放在代碼周圍,並在except:塊中使用pass來忽略錯誤

try:
    with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
        for line in myfile:
            if h in line:
                save_file.write("Number = " + line + "")
                print("Number = " + line + "")
except FileNotFoundError:
    pass

try:然后有你想要嘗試的縮進代碼塊,如果出現錯誤,它將 go 到except:代碼塊並在那里做任何你想做的事情。

try:
    with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
        for line in myfile:
            if h in line:
                save_file.write("Number = " + line + "")
                print("Number = " + line + "")
except FileNotFoundError:
    print("The error was found!")
    # or do whatever other code you want to do, maybe nothing (so pass)
    # maybe let the user know somehow, maybe do something else.
    
try:
   with open("file.txt") as myfile, open("save.txt", 'a') as save_file:

    for line in myfile:
        if h in line:
            save_file.write("Number = " + line + "")
            print("Number = " + line + "")
except NameError:
   print("file doesn't exist")
finally:
   print("regardless of the result of the try- and except blocks, this block will be executed")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM