简体   繁体   English

在python 2.7中使用openpyxl时,模式或文件名无效

[英]Invalid mode or filename when using openpyxl in python 2.7

I am trying to write something in an existing workbook with the openpyxl tools. 我正在尝试使用openpyxl工具在现有工作簿中编写一些内容。

But i am getting Err no 22 and dont know why. 但是我得到22号错误,不知道为什么。

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. 只需将\\更改为/即可。

In Python the \\ is used in strings to escape characters. 在Python中, \\用于字符串中以转义字符。 You can avoid this by using "raw strings" by prefixing with "r". 您可以通过在前缀为“ r”的情况下使用“原始字符串”来避免这种情况。 So r'J:\\Python_Script\\book2.xls' should work. 因此r'J:\\Python_Script\\book2.xls'应该可以正常工作。

However, when working with paths it's most common to use the os.path module to make sure this are correct. 但是,在使用路径时,最常见的是使用os.path模块来确保这是正确的。

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

This is invaluable when writing portable code. 在编写可移植代码时,这是无价的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM