我正试图将两个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)

有人能解释一下为什么这样吗?文件名和文件扩展名在每一位代码中都是相同的,并且使用了相同的参数,所以我不明白为什么一个创建了无效文件,而另一个则没有.

推荐答案

您需要关闭文件以正确写入更改并使其有效:

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)
V_writer.close()

with语句会自动为您执行此操作(通过调用__exit__方法,该方法只会运行close):

V_writer.__exit__??

Source:
    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_value: BaseException | None,
        traceback: TracebackType | None,
    ) -> None:
        self.close()

Python相关问答推荐

返回nxon矩阵的diag元素,而不使用for循环

'discord.ext. commanders.cog没有属性监听器'

处理(潜在)不断增长的任务队列的并行/并行方法

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

输出中带有南的亚麻神经网络

无法通过python-jira访问jira工作日志(log)中的 comments

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

加速Python循环

Python键入协议默认值

try 将一行连接到Tensorflow中的矩阵

pyscript中的压痕问题

组/群集按字符串中的子字符串或子字符串中的字符串轮询数据框

迭代嵌套字典的值

启动带有参数的Python NTFS会导致文件路径混乱

处理具有多个独立头的CSV文件

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

如何将数据帧中的timedelta转换为datetime

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion

用0填充没有覆盖范围的垃圾箱

有什么方法可以在不对多索引DataFrame的列进行排序的情况下避免词法排序警告吗?