以下代码成功创建了单独的文件,但必须在恢复模式下打开的最后一个文件除外。我试着调查所有可能的问题,但没有成功。
问题:根据以下代码,是否有任何原因导致大多数文件创建正确,而最后一个文件已损坏?
for key, value in sorted(mdm_sheet_to_df_map.items()):
mdm_group = value.groupby('MDM')
for MDM, group_df in mdm_group:
attachment_mdm = attachment_path_mdm / f'{MDM}' / f'Q221 New Accounts - {MDM} - {today_string1}.xlsx'
attachment1_mdm = os.makedirs(os.path.dirname(attachment_mdm), exist_ok=True)
try:
writer = ExcelWriter(attachment_mdm, engine = 'openpyxl', mode="a")
except FileNotFoundError:
writer = ExcelWriter(attachment_mdm, engine = 'openpyxl')
group_df.to_excel(writer, sheet_name =f'{key}', index=False)
writer.save()
writer.close()
EDIT:运行脚本时,Python中不会出现异常/错误。当我尝试打开正在恢复的最后一个文件时,发现了这个问题。所有其他文件正常打开。
我现在也面临同样的问题。对我来说,解决办法是让作者";用";以及不使用.save和.close方法。
for key, value in sorted(mdm_sheet_to_df_map.items()):
mdm_group = value.groupby('MDM')
for MDM, group_df in mdm_group:
attachment_mdm = attachment_path_mdm / f'{MDM}' / f'Q221 New Accounts - {MDM} - {today_string1}.xlsx'
attachment1_mdm = os.makedirs(os.path.dirname(attachment_mdm), exist_ok=True)
with pd.ExcelWriter(attachment_mdm, engine = 'openpyxl') as writer:
group_df.to_excel(writer, sheet_name =f'{key}', index=False)
仍然不确定如何处理FileNotFound。但我认为这应该有助于走这条路。