1

I am trying to write something in an existing workbook with the openpyxl tools.

But i am getting Err no 22 and dont know why.

My Script looks like this :

#Reading & writing to a workbook

from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter

wb = Workbook()

dest_filename = 'J:\Python_Script\book2.xls'

ws = wb.active

ws.title = "Tabelle 1"

for col_idx in range(1, 40):
     col = get_column_letter(col_idx)
     for row in range(1, 600):
         ws.cell('%s%s'%(col, row)).value = '%s%s' % (col, row)

ws = wb.create_sheet()

ws.title = 'Pi'

ws['F5'] = 3.14

wb.save(filename = dest_filename)

and this is the Console output with the error message i got :

//------------------

Traceback (most recent call last):
File "J:/Python_Script/xlsx_test.py", line 26, in <module>
wb.save(filename = dest_filename)
File "build\bdist.win32\egg\openpyxl\workbook\workbook.py", line 281, in save
save_workbook(self, filename)
File "build\bdist.win32\egg\openpyxl\writer\excel.py", line 214, in save_workbook
writer.save(filename)
File "build\bdist.win32\egg\openpyxl\writer\excel.py", line 196, in save
archive = ZipFile(filename, 'w', ZIP_DEFLATED)
File "C:\Python27\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 22] invalid mode ('wb') or   filename: 'J:\\Python_Script\x08ook2.xls'

//----------------------

I am not sure why the file path is different now, also the file name different from the filename in the input section.

thanks

EDIT:

Solved. Just had to change from \ to / in the path.

HightronicDesign
  • 699
  • 1
  • 9
  • 15

1 Answers1

2

In Python the \ is used in strings to escape characters. You can avoid this by using "raw strings" by prefixing with "r". So r'J:\Python_Script\book2.xls' should work.

However, when working with paths it's most common to use the os.path module to make sure this are correct.

dest_filename = os.path.join("J:", "Python_Script", "book2.xlsx")

This is invaluable when writing portable code.

Charlie Clark
  • 18,477
  • 4
  • 49
  • 55