我正试图将两个Pandas打印机导出到同一个Excel文件,在不同的工作表.
下面的代码运行正常,但它创建的文件大小为0kb.当我试图在Excel中打开它时,我得到的消息是"Excel cannot open the file myfile.xlsx because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file":
V_writer = pd.ExcelWriter("myfile.xlsx", mode = 'w')
V_df_1.to_excel(V_writer, sheet_name = "df_1", index = False)
V_df_2.to_excel(V_writer, sheet_name = "df_2", index = False)
但是,下面的代码运行得很好:
with pd.ExcelWriter("myfile.xlsx", mode = 'w') as V_writer:
V_df_1.to_excel(V_writer, sheet_name = "df_1", index = False)
V_df_2.to_excel(V_writer, sheet_name = "df_1", index = False)
有人能解释一下为什么这样吗?文件名和文件扩展名在每一位代码中都是相同的,并且使用了相同的参数,所以我不明白为什么一个创建了无效文件,而另一个则没有.