我正在使用pandas中的函数
.to_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\zipfile.py:1816 in writestr
with self.open(zinfo, mode='w') as dest:
File ~\AppData\Local\Programs\Python\Python310\lib\zipfile.py:1180 in close
self._fileobj.seek(self._zinfo.header_offset)
OSError: [Errno 9] Bad file descriptor
正如我在评论中提到的,问题出在文件权限或文件被锁定/使用时。
尝试这样。
以
w
写入模式运行。
with pd.ExcelWriter('output.xlsx', mode='w', if_sheet_exists='replace') as writer:
df.to_excel(writer, sheet_name="MySheet", index=False)
或者使用不同的引擎
df.to_excel('output.xlsx', sheet_name="MySheet", engine='xlsxwriter', index=False)