在python 2.7中使用openpyxl时无效的模式或文件名 [英] Invalid mode or filename when using openpyxl in python 2.7

查看:227
本文介绍了在python 2.7中使用openpyxl时无效的模式或文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用openpyxl工具在现有工作簿中编写一些内容.

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

但是我得到22号错误,不知道为什么.

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

我的脚本如下:

#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.

谢谢

已解决.只需将\更改为/即可.

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

推荐答案

在Python中,\用于字符串中的转义字符.您可以通过在前缀为"r"的情况下使用原始字符串"来避免这种情况.因此r'J:\Python_Script\book2.xls'应该可以工作.

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.

但是,在使用路径时,最常见的是使用os.path模块来确保这是正确的.

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.

这篇关于在python 2.7中使用openpyxl时无效的模式或文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆