我不太懂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'
并且不抛出此错误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:
block 中使用 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
关于python - 如何添加 try & except 构造以便脚本忽略不存在文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73976355/