"OSError: [Errno 22] Invalid argument:" while trying to save an edited workbook with save()

"OSError: [Errno 22] Invalid argument:" while trying to save an edited workbook with save()

我在与 .py 文件相同的目录中有一个 .xls 文件。 虽然如果我不覆盖现有文件它工作正常。

import xlrd, xlwt
from xlutils.copy import copy

rb2=xlrd.open_workbook("TEST_info.xls",on_demand=True)

wb2=copy(rb2)
ws2=wb2.get_sheet(0)
ws2.write(0,1,'DIFFERENt value')
wb2.save("TEST_info.xls")

File "C:\Python_User\Excel_spreadsheet_proj\excel_proj_env\Scripts\main.py", line 9, in wb2.save("TEST_info.xls") File "C:\Python_User\Excel_spreadsheet_proj\excel_proj_env\lib\site-packages\xlwt\Workbook.py", line 710, in save doc.save(filename_or_stream, self.get_biff_data()) File "C:\Python_User\Excel_spreadsheet_proj\excel_proj_env\lib\site-packages\xlwt\CompoundDoc.py", line 262, in save f = open(file_name_or_filelike_obj, 'w+b') OSError: [Errno 22] Invalid argument: 'TEST_info.xls'

根据 https://xlrd.readthedocs.io/en/latest/on_demand.html 的文档:

on_demand=True and BIFF version >= 5.0: open_workbook() loads global data and returns without releasing resources.

您应该将 on_demand=True 设置为 False 以便 rb2 释放底层资源,或者在尝试保存副本之前调用 rb2.release_resources()

我最终导入了“os”并写成:

if(os.path.exists(file)):
    os.remove(file)
wb.save(file)