You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas的to_excel()函数时遭遇OSError: [Errno 9] Bad file descriptor错误的求助

使用pandas的to_excel()函数时遭遇OSError: [Errno 9] Bad file descriptor错误的求助

各位好,我在使用pandas的.to_excel()函数导出Excel文件时遇到了棘手的问题,想请教大家怎么解决!

我的代码如下:

import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]])
with pd.ExcelWriter('output.xlsx') as writer:
    df.to_excel(writer, sheet_name="MySheet")

运行这段代码后,直接抛出了错误:OSError: [Errno 9] Bad file descriptor

我已经确认目标Excel文件确实存在,但绝对没有在其他程序中打开。

我的环境版本信息:

  • Python 3.10.11
  • pandas 2.2.3
  • openpyxl 3.1.5

完整的报错回溯信息如下:

with pd.ExcelWriter('output.xlsx') as writer:

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\excel\_base.py:1353 in __exit__
    self.close()

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\excel\_base.py:1357 in close
    self._save()

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\excel\_openpyxl.py:110 in _save
    self.book.save(self._handles.handle)

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\workbook\workbook.py:386 in save
    save_workbook(self, filename)

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\writer\excel.py:294 in save_workbook
    writer.save()

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\writer\excel.py:275 in save
    self.write_data()

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\writer\excel.py:60 in write_data
    archive.writestr(ARC_APP, tostring(props.to_tree()))

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\zipfile.py:1816 in writestr
    with self.open(zinfo, mode='w') as dest:

  File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\zipfile.py:1180 in close
    self._fileobj.seek(self._zinfo.header_offset)

OSError: [Errno 9] Bad file descriptor

有没有朋友遇到过类似的问题?或者能帮我分析下可能的原因和解决办法吗?

备注:内容来源于stack exchange,提问作者Rémi Baudoux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 12:49:53