处理Python文本文件异常
如果用float替换文本文件中的所有数据,则在字符串意外更改期间,必须出现ValueError错误。我想作为一个例外忽略字符串,只显示float。我该怎么办处理Python文本文件异常,python,Python,如果用float替换文本文件中的所有数据,则在字符串意外更改期间,必须出现ValueError错误。我想作为一个例外忽略字符串,只显示float。我该怎么办 您的try except块的范围太大。它包括文件的整个扫描。您应该将其拆分以处理不同点的错误: try: f1 = open("c:\\temp\\MP11Data1.txt") lines = f1.readlines() list1 = [] for line in lines:
您的try except块的范围太大。它包括文件的整个扫描。您应该将其拆分以处理不同点的错误:
try:
f1 = open("c:\\temp\\MP11Data1.txt")
lines = f1.readlines()
list1 = []
for line in lines:
k1 = float(line)
list1.append(k1)
f1.close()
except ValueError:
pass
这样,程序不同点上的错误将分别处理。可能会在
k1=float(line)
周围添加另一个try/catch?上面的注释是正确的答案,那么我能做什么?
lines = [] ## Just for security if there is an IOError.
## First handle the file
try:
f1 = open("c:\\temp\\MP11Data1.txt")
lines = f1.readlines()
f1.close()
except:
print("The file could not be loaded")
## Now you can scan and process the contents
list1 = []
for line in lines:
try:
k1 = float(line)
list1.append(k1)
except:
print("This line did not contain a number: ",line)