如何添加 try & except 构造,以便脚本忽略没有文件



我真的不懂Python语言,所以我向专家寻求帮助。我有一个简单的脚本,我需要添加一个结构到它

try:
except:

这是必要的,以便脚本忽略不存在CCD_ 1文件并且不显示错误。

如果文件"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',而不抛出这个错误Traceback(最后一次调用(?

脚本代码:

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

您执行'file.txt'0,然后有您想要尝试的缩进代码块,如果出现错误,它将转到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")

最新更新