首页 > 解决方案 > 从给定目录中删除损坏的 xlsx 文件

问题描述

更新

特定目录中的某些.xlsx文件已损坏,因为尝试打开工作簿时的 windows 消息如下:

Excel 无法打开文件“filename.xlsx”,因为文件格式或文件扩展名无效。验证文件没有损坏,并且文件扩展名与文件格式匹配。`

我想知道是否可以检测到这些损坏的文件并将其从目录中删除。

我的试用:

############### path settlement and file names ##########
path_reportes = os.path.join(os.getcwd(), 'Reports', 'xlsx_folder')
file_names = os.listdir(path_reportes)
overall_df = dict()

############## concatenate all reports ##################

for file_name in file_names:

    data_file_path = os.path.join(path_reportes, file_name)
    """
    try open spreadsheets, save them and store them in a dictionary key
    except when the file is corrupted, if so, remove it from the 
    folder
    """
    try:
     # Start by opening the spreadsheet and selecting the main sheet
        workbook = openpyxl.load_workbook(filename=data_file_path)
        sheet = workbook.active
    
     # Save the spreadsheet
        workbook.save(filename=data_file_path)
        df_report_dict = pd.read_excel(data_file_path, sheet_name=None, engine='openpyxl')
    
        for key in df_report_dict:
            
            df_report_dict[key]['report_name'] = file_name
            
            try:
                  overall_df[key] = overall_df[key].append(df_report_dict[key], ignore_index=True)
            except:
                  overall_df[key] = df_report_dict[key]
                
                
    # when file corrupted then remove it from the folder             
    except BadZipFile:
                   os.remove(data_file_path)
            

这会引发下一个错误:

NameError:未定义名称“BadZipFile”

是否可以检测损坏的文件?我怎么能应付他们?

标签: pythonexceloperating-systemtry-catch

解决方案


当您尝试加载损坏的 Excel 文件时会遇到什么异常?运行该实验,然后编写一个try-except块来处理该条件。

try:
    # load PANDAS df

except CorruptedExcelFile:
    os.remove(filename)

从您引用的帖子看来,问题似乎是在尝试解压缩文件时发生的,因此适当的例外是BadZipFile. 在except声明中使用它。您可能希望将处理限制为特定异常,因为结果是删除了有问题的文件。


推荐阅读