Skip to main content
 首页 » 编程设计

Python:如何将引发的异常识别为错误并通过 except 语句传递它

2025年05月04日15JustinYoung

我正在提取电子表格并意识到有些电子表格将受密码保护,因此下面的代码将无法读取某些电子表格,这很好。我试图通过 except 行传递这些电子表格,并且我从 zipfile 导入了 BadZipfile 以尝试将它们识别为错误。

但是,except 函数不会将 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。

其次,要捕获多种类型的错误,您可以执行 except (KeyError, BadZipFile): 而不是 except KeyError 或 BadZipFile:,它的计算结果只是 except KeyError(阅读 或 的工作原理)