【发布时间】:2020-05-19 04:36:33
【问题描述】:
编辑:我发现我的异常没有被捕获的原因是 因为它们实际上是由不同的函数抛出的 我在哪里放了 try except 块。菜鸟失误。如果一个模组想要删除 或建议我如何编辑问题。因为它,我没有删除它 有答案。
我正在尝试向我的代码添加一些错误处理,该代码使用pandas 库从 Excel 电子表格中读取数据。 我之前没有在 Python 中做过这种类型的异常处理,所以不确定我做错了什么。
在我的以下代码 sn-p 中,当我将 xlsx 文件放在我的程序找不到的地方时,FileNotFoundError 异常工作得很好。我的程序干净地退出并显示消息并具有正确的退出状态。
try:
xdf = pd.read_excel(xlsxdir + 'web_targets.xlsx', 'targets', skiprows=[0], index_col=None, na_values=['NA'], usecols = "A:F")
except KeyError as e:
print("Expected column headers not found")
sys.exit(1)
except TypeError as e:
print("Type Error")
sys.exit(1)
except FileNotFoundError as e:
print("Excel file not found " + str(e))
sys.exit(1)
不幸的是,当程序可以找到该文件,但有一个意外的列键/标题,KeyError 或 ValueError 异常捕获,我得到以下回溯:
Traceback (most recent call last):
File "/home/justin/projects/web_targets/venv/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 4410, in get_value
return libindex.get_value_at(s, key)
File "pandas/_libs/index.pyx", line 44, in pandas._libs.index.get_value_at
File "pandas/_libs/index.pyx", line 45, in pandas._libs.index.get_value_at
File "pandas/_libs/util.pxd", line 98, in pandas._libs.util.get_value_at
File "pandas/_libs/util.pxd", line 83, in pandas._libs.util.validate_indexer
TypeError: 'str' object cannot be interpreted as an integer
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./create_new_configs.py", line 60, in <module>
for record in xdfToDict(xdf):
File "./create_new_configs.py", line 29, in xdfToDict
'app': row['App'],
File "/home/justin/projects/web_targets/venv/lib/python3.6/site-packages/pandas/core/series.py", line 871, in __getitem__
result = self.index.get_value(self, key)
File "/home/justin/projects/web_targets/venv/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 4418, in get_value
raise e1
File "/home/justin/projects/web_targets/venv/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 4404, in get_value
return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
File "pandas/_libs/index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 90, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'App'
我最初没有TypeError 异常,但我想可能是因为它是第一个异常,你必须先“捕获”它,所以我添加了它,但没有任何改变。
我已经进行了一些搜索,据我所知,我正在做与例如示例相同的操作。 KeyValue 异常。
我希望能够捕获一些潜在的数据输入错误并返回到 BASH 脚本,我将使用合适的退出代码调用此程序。
【问题讨论】:
标签: python pandas try-catch keyerror except