python - 从给定目录中删除损坏的 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”
是否可以检测损坏的文件?我怎么能应付他们?
解决方案
当您尝试加载损坏的 Excel 文件时会遇到什么异常?运行该实验,然后编写一个try-except
块来处理该条件。
try:
# load PANDAS df
except CorruptedExcelFile:
os.remove(filename)
从您引用的帖子看来,问题似乎是在尝试解压缩文件时发生的,因此适当的例外是BadZipFile
. 在except
声明中使用它。您可能希望将处理限制为特定异常,因为结果是删除了有问题的文件。
推荐阅读
- javascript - jQuery多步表单验证
- c++ - 在 C++20 获得批准之前,我应该如何使用 day-since-epoch 值?
- bookshelf.js - Bookshelf.js: one-to-many relationship setup
- python - Points inside polygon in PostGIS
- rest - 移动应用 + REST API 身份验证
- r - KableExtra 有条件地格式化列上的特定行
- string - How to avoid empty lists to be appended & parentheses and brackets
- angular - 取消选择线所有图表线应禁用
- javascript - Keydown 反复触发。可以避免吗?
- doctrine-orm - Pagerfanta 不喜欢我的教义查询