之前一直没有问题,但最近突然就这样了,我把这段写在一个单独的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:
代码本身测试:
这个代码在本地新建环境下使用是正常的
错误解析:
解决错误的思路:
源码查找:
# 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)
根据提供的信息,大概能分析出这些信息,希望对你有帮助。
可能有其它程序正在用这个表 数据.xlsx?