Python:如何将exception提升识别为错误,并通过except语句传递

我正在提取电子表格,并意识到一些将被密码保护,因此一些电子表格将无法被下面的代码读取,这是好的。 我试图通过这些电子表格通过除了行,我已经从zipfile中导入BadZipfile,以尝试将它们识别为错误。

但是,除了函数不认可BadZipfile作为一个错误,它仍然会提高Traceback(下面)中的错误。 我希望通过将except行留空,它会传递任何错误,并且会再次循环以在其余文件上运行try语句,但是它似乎并不认为BadZipfile是一个错误。

在except语句中也需要KeyError,因为有些电子表格没有我想要提取的索引标签。 也许我应该通过任何例外,因为进一步的错误可能会从我还没有结束的文件中产生。 我宁愿处理在这一点上工作的任何电子表格,稍后再调整错误。

因此,如何确保BadZipfile被识别为错误,然后使用except语句来传递任何错误?

import itertools import glob from openpyxl import load_workbook from pandas import DataFrame import pandas as pd import os from zipfile import BadZipfile def get_data(ws): for row in ws.values: row_it = iter(row) for cell in row_it: if cell is not None: yield itertools.chain((cell,), row_it) break def read_workbook(file_): wb = load_workbook(file_, data_only=True) for sheet in wb.worksheets: ws = sheet return DataFrame(get_data(ws)) path =r'dir' allFiles = glob.glob(path + "/*.xlsx") frame = pd.DataFrame() list_ = [] for file_ in allFiles: parsed_file = read_workbook(file_) parsed_file['filename'] = os.path.basename(file_) parsed_file.set_index(parsed_file.columns[0], inplace = True) parsed_file.index.str.strip() try: parsed_file.loc["Staff" : "Total Staff"].copy() list_.append(parsed_file) except KeyError or BadZipfile: pass frame = pd.concat(list_) print(frame.dropna(axis='columns', thresh=2, inplace = True)) 

错误

 Traceback (most recent call last): File "<ipython-input-47-2d5508ddf805>", line 1, in <module> runfile('C:dir.py', wdir='C:dir') File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:dir.py", line 35, in <module> parsed_file = read_workbook(file_) File "C:dir.py", line 25, in read_workbook wb = load_workbook(file_, data_only=True) File "C:\ProgramData\Anaconda2\lib\site-packages\openpyxl\reader\excel.py", line 164, in load_workbook archive = _validate_archive(filename) File "C:\ProgramData\Anaconda2\lib\site-packages\openpyxl\reader\excel.py", line 121, in _validate_archive archive = ZipFile(f, 'r', ZIP_DEFLATED) File "C:\ProgramData\Anaconda2\lib\zipfile.py", line 770, in __init__ self._RealGetContents() File "C:\ProgramData\Anaconda2\lib\zipfile.py", line 813, in _RealGetContents raise BadZipfile, "File is not a zip file" BadZipfile: File is not a zip file 

首先,检查你的堆栈跟踪。 你没有try/except错误被抛出的地方。

第二,要捕获多种types的错误, except (KeyError, BadZipFile): except KeyError or BadZipFile: ,它只是计算except KeyError except KeyError or BadZipFile: except KeyError (请except KeyError or BadZipFile:阅读or如何工作)

从error handling的文档页面 :

 try: # your code except (KeyError, BadZipfile): pass 

如果你想对错误做些什么,你可以使用

 try: # your code except (KeyError, BadZipfile) as err: # do something 

它看起来像你的read_workbook函数中实际发生的错误,当你调用语句load_workbook所以你没有捕捉错误发生时。