导入excel文件错误python pandas

时间:2013-03-28 12:26:40

标签: python excel pandas spyder

我无法使用ExcelFile()将Excel文件加载到数据框中。我导入了pandas,xlrd和openpyxl。我正在使用spyder进行交互式数据分析。 我是熊猫和蟒蛇的新手,所以我会想要一个初学者可以理解的答案。有人能帮助我吗?

>>> import xlrd
>>> import openpyxl
>>> from pandas import *
>>> xls = ExcelFile('C:\RWFC\test.xls')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 1294, in __init__
self.book = xlrd.open_workbook(path_or_buf)
File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 400, in open_workbook
f = open(filename, "rb")
IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\RWFC\test.xls'

2 个答案:

答案 0 :(得分:4)

问题出在这一行:

>>> xls = ExcelFile('C:\RWFC\test.xls')

反斜杠具有特殊含义。例如,普通字符串中的字符“\ t”是制表符:

>>> "\t"
'\t'
>>> len("\t")
1

这就是您的错误消息中的原因:

IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\RWFC\test.xls'

你看到R - \R前面的双斜线没有任何特殊含义,所以它知道你的意思是一个“真正的”斜线:

>>> s = "\\"
>>> s
'\\'
>>> print s
\
>>> len(s)
1

\t确实有特殊含义。要解决此问题,您可以使用“原始字符串”,并在字符串文字前添加“r”:

>>> "C:\RWFC\test.xls"
'C:\\RWFC\test.xls'
>>> r"C:\RWFC\test.xls"
'C:\\RWFC\\test.xls'

或者,您可以简单地使用正斜杠 - Windows支持 - 并避免所有麻烦:

>>> "C:/RWFC/test.xls"
'C:/RWFC/test.xls'

无论哪种方式都应该有效。

答案 1 :(得分:0)

我遇到了类似的问题。我用这种方式解决了这个问题:

path = r"Drive:\path\to\your\file.extension"
workbook = xlrd.open_workbook(path) ##assuming you have imported xlrd already

希望这会有所帮助。 :)