Search code examples
pythonpython-3.xxlwterrno

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


I have an .xls file in the same directory with my .py file. Although it works fine if I'm not overwriting an existing file.

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'


Solution

  • I ended up with importing "os" and writing:

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