python导入excel文件,报错

阿呆上大学 发布于 2016/02/22 19:13
阅读 1K+
收藏 0

尝试导入excel文件操作,编写了以下代码,

import xlrd
workbook = xlrd.open_workbook('D:\ben.qin\Desktop\1.xls')
worksheets = workbook.sheet_names()
print('worksheets is %s' %worksheets)

报出以下错误,还请帮忙指点错误

runfile('D:/工具/Python/实例/读取文件.py', wdir='D:/工具/Python/实例')
Traceback (most recent call last):


  File "<ipython-input-1-c3571d5c5ef5>", line 1, in <module>
    runfile('D:/工具/Python/实例/读取文件.py', wdir='D:/工具/Python/实例')

  File "D:\工具\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)

  File "D:\工具\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 88, in execfile
    exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

  File "D:/工具/Python/实例/读取文件.py", line 9, in <module>
    workbook = xlrd.open_workbook('D:\ben.qin\Desktop\1.xls')

  File "D:\工具\Anaconda3\lib\site-packages\xlrd\__init__.py", line 394, in open_workbook
    f = open(filename, "rb")

OSError: [Errno 22] Invalid argument: 'D:\x08en.qin\\Desktop\x01.xls'

加载中
0
ChalieJiang
ChalieJiang

报错原因是方法中的参数为转义字符。

open_workbook(r'D:dir')这样写,或者open_workbook('D:\\dir')这样写,或者为open_workbook('D:/dir')这样写

1
ChalieJiang
ChalieJiang

引用来自“ChalieJiang”的评论

报错原因是方法中的参数为转义字符。

open_workbook(r'D:dir')这样写,或者open_workbook('D:\\dir')这样写,或者为open_workbook('D:/dir')这样写

更正:open_workbook(r'D:dir')少写一个反斜扛,改为这样的格式open_workbook(r'D:\dir\dir\dir')
返回顶部
顶部