python用openpyxl保存excel时出现OSError: [Errno 9] Bad file descriptor,如何解决?

问题遇到的现象和发生背景

之前一直没有问题,但最近突然就这样了,我把这段写在一个单独的py文件里,依然是报错

问题相关代码,请勿粘贴截图

import openpyxl
workbook = openpyxl.load_workbook('数据.xlsx') # 返回一个workbook数据类型的值
sheet = workbook.active # 获取活动表
sheet['A1'] = 20 # 获取活动表
workbook.save('数据.xlsx')

运行结果及报错内容

Traceback (most recent call last):
File "C:/Users/M/Desktop/DQN/123.py", line 6, in
workbook.save('数据.xlsx')
OSError: [Errno 9] Bad file descriptor
Exception ignored in:

代码本身测试:
这个代码在本地新建环境下使用是正常的
错误解析:

  1. OSError: [Errno 9] Bad file descriptor
  2. Bad file descriptor 错误的文件描述符--代表:当代码尝试对已关闭(未打开)的文件执行操作/活动时,会生成错误的文件描述符错误

解决错误的思路:

  1. 重启电脑排除其他应用程序导致的错误
  2. 配置一个新的虚拟环境,确定是否由环境配置错误、包之间的冲突、版本问题等
  3. 寻找此文件是否在其他代码中被使用或者重复关闭

源码查找:

  1. 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
    
  2. 涉及到的可能的关闭操作:
# 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)

根据提供的信息,大概能分析出这些信息,希望对你有帮助。

可能有其它程序正在用这个表 数据.xlsx?