代码本身测试:
这个代码在本地新建环境下使用是正常的
错误解析:
- OSError: [Errno 9] Bad file descriptor
- Bad file descriptor 错误的文件描述符--代表:当代码尝试对已关闭(未打开)的文件执行操作/活动时,会生成错误的文件描述符错误
解决错误的思路:
- 重启电脑排除其他应用程序导致的错误
- 配置一个新的虚拟环境,确定是否由环境配置错误、包之间的冲突、版本问题等
- 寻找此文件是否在其他代码中被使用或者重复关闭
源码查找:
- workbook.save函数
# https://openpyxl.readthedocs.io/en/latest/_modules/openpyxl/writer/excel.html#save_workbook
def save_workbook(workbook, filename):
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
writer = ExcelWriter(workbook, archive)
writer.save()
return True
- 涉及到的可能的关闭操作:
# https://openpyxl.readthedocs.io/en/latest/_modules/openpyxl/writer/excel.html#save_workbook
class ExcelWriter(object):
def save(self):
"""Write data into the archive."""
self.write_data()
self._archive.close()
# 涉及到标准库 zipfile的使用:https://docs.python.org/zh-cn/3/library/zipfile.html
# https://github.com/python/cpython/blob/3.10/Lib/zipfile.py
def close(self):
"""Close the file, and for mode 'w', 'x' and 'a' write the ending
records."""
if self.fp is None:
return
if self._writing:
raise ValueError("Can't close the ZIP file while there is "
"an open writing handle on it. "
"Close the writing handle before closing the zip.")
try:
if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
self._write_end_record()
finally:
fp = self.fp
self.fp = None
self._fpclose(fp)
根据提供的信息,大概能分析出这些信息,希望对你有帮助。