Python: Try, Continue, Except语句在for循环中
Python: Try, Continue, Except statement in for loop
我刚刚了解了解决 for 循环中遇到的错误的概念。我有一个从本地计算机读入的文件列表,我想将它们作为 pandas 数据帧读入。
假设我有一个文件列表,每个文件作为 "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]
这似乎有点工作,但它打印了 except 语句 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
我刚刚了解了解决 for 循环中遇到的错误的概念。我有一个从本地计算机读入的文件列表,我想将它们作为 pandas 数据帧读入。
假设我有一个文件列表,每个文件作为 "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]
这似乎有点工作,但它打印了 except 语句 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