[英]Python: Try, Continue, Except statement in for loop
我实际上只是了解了解决在for循环中遇到的错误的概念。 我有从本地计算机读取的文件列表,我想以熊猫数据框的形式读取它们。
假设我有一个文件列表,每个文件都列为“ A”,“ B”和“ C”列。 如果有特定的列,可以说file3.tbl中的“ B”列,而我的计算机上的文件缺少该列,我想继续进行for循环。
list = ['file1.tbl', 'file2.tbl', 'file3.tbl']
for i in range(len(list)):
data = pandas.read_csv(list[i])
try:
b = data['B']
continue
except Exception:
print "Column B not included in file: ", list[i]
这似乎有些奏效,但它打印出除len(list)语句外的次数,如下所示:
Column B not included in file: file3.tbl
Column B not included in file: file3.tbl
Column B not included in file: file3.tbl
有没有办法让它只为特定的迭代打印一次?
如评论中所提示,您可能遇到名称空间问题。 这是一些清理过的代码,应该为每个Exception
唯一打印。 它包含与注释一致的Pythonic建议。
对于三个类似csv的文件"file1.tbl", "file2.tbl", "file3.tbl"
,我得到以下信息:
import pandas as pd
filenames = ["file1.tbl", "file2.tbl", "file3.tbl"] # @John Gordon
for fn in filenames:
data = pd.read_csv(fn)
try:
b = data['B']
except (KeyError): # @Ryan
print("Column B not included in file: ", fn)
else:
# Do something with b (optional)
pass
# Column B not included in file: file1.tbl
# Column B not included in file: file2.tbl
# Column B not included in file: file3.tbl
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.