更新
特定目录中的某些.xlsx
文件已损坏,因为尝试打开工作簿时的窗口消息如下:
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)
引发下一个错误:
名称错误:名称"BadZipFile"未定义
是否可以检测损坏的文件?我该如何处理它们?
如果您仍然存在未定义BadZipFile
的问题,则:
由于异常类BadZipFile
在模块zipfile
中,您只需要一个import
语句,例如:
from zipfile import BadZipFile
然后您应该能够处理异常。
当您试图加载损坏的Excel文件时,会出现什么异常?运行该实验,然后编写一个try-except
块来处理该条件。
try:
# load PANDAS df
except CorruptedExcelFile:
os.remove(filename)
从您引用的帖子来看,问题似乎是在尝试解压缩文件时发生的,因此适当的异常是BadZipFile
。在except
语句中使用它。您可能希望将处理限制为特定的异常,因为结果是删除有问题的文件。
场景:我在名为xlsx_folder
的目录中创建了三个相同的excel文件,并希望将所有文件合并到一个data frame
中。为此,我建议使用glob
,而不是使用os
模块。
import os # for deleting corrupted file
import glob # to list out a specific file type
import pandas as pd
# here is a list of all the file in the directory
print(glob.glob("xlsx_folder/*.xlsx"))
输出:
['xlsx_folder\file1 - Copy (2).xlsx',
'xlsx_folder\file1 - Copy.xlsx',
'xlsx_folder\file1.xlsx',
'xlsx_folder\~$file1.xlsx']
注意:在windows中,当excel文件打开时,它会创建一个带有~$
符号的临时文件,这是一个临时文件(在这种情况下,我认为它是一个损坏的文件(。
现在,您可以从目录中读取所有文件,并制作一个数据帧,如下所示:
overall_df = []
for f in glob.glob("xlsx_folder/*.xlsx"):
try:
overall_df.append(pd.read_excel(f)) # if there is an encoding error, handle it here
except Exception as err:
print(f"Unable to Read: {f}.n{err}") # use format if not familiar with f-strings
# delete the file with os.remove
# os.remove(f)
overall_df = pd.concat(overall_df, ignore_index = True)
这会打印一个警告语句,如:
Unable to Read: xlsx_folder~$file1.xlsx.
[Errno 13] Permission denied: 'xlsx_folder\~$file1.xlsx'