我正在尝试创建一个尝试,但捕获了 3 个错误:
我确实尝试做第一个,如果文件不是 txt 文件,则会抛出错误消息,但我也收到错误消息,说“str”对象没有属性“包含”
try:
file_name = input("Enter file name: ")
assert not file_name.contains(".txt")
except AssertionError:
("Error, must be a txt file")
file_fh = open(file_name)
counter = 0
avg = 0
for line in file_fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
avg += float(line[20:-1].strip())
counter = counter + 1
print("Average spam confidence:", round(avg / counter, 4))
答案 0 :(得分:1)
如果您希望能够在大代码块中的任何位置捕获异常,则整个事情需要在同一个 try
块中:
try:
file_name = input("Enter file name: ")
assert ".txt" in file_name, "Error, must be a txt file"
file_fh = open(file_name) # may raise FileNotFoundError
counter = 0
avg = 0
for line in file_fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
avg += float(line[20:-1].strip())
counter = counter + 1
assert counter, "File is empty!"
print("Average spam confidence:", round(avg / counter, 4))
except (AssertionError, FileNotFoundError) as e:
print(e)
在本例中,如果不满足条件,assert
语句显然会引发带有给定消息的 AssertionError
。如果文件丢失,open
调用将引发 FileNotFoundError
,因此要处理这种情况,您需要做的就是确保您的 except
块包含 FileNotFoundError
。