问题描述
我的.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")
文件 “ C:\ Python_User \ Excel_spreadsheet_proj \ excel_proj_env \ Scripts \ main.py”, 第9行 wb2.save(“ TEST_info.xls”)文件“ C:\ Python_User \ Excel_spreadsheet_proj \ excel_proj_env \ lib \ site-packages \ xlwt \ Workbook.py”, 710行,保存 doc.save(filename_or_stream,self.get_biff_data())文件“ C:\ Python_User \ Excel_spreadsheet_proj \ excel_proj_env \ lib \ site-packages \ xlwt \ CompoundDoc.py”, 第262行,保存 f =打开(file_name_or_filelike_obj,'w + b') OSError:[Errno 22]无效的参数:'TEST_info.xls'
解决方法
根据https://xlrd.readthedocs.io/en/latest/on_demand.html上的文档:
SHOW CREATE TABLE
和on_demand=True
:BIFF version >= 5.0
加载全局数据并返回而不释放资源。
您应该将open_workbook()
设置为on_demand=True
,以便False
释放基础资源,或者在尝试保存副本之前调用rb2
。
我最终导入了“ os”并编写:
if(os.path.exists(file)):
os.remove(file)
wb.save(file)