导入excel文件错误pythonpandas
我无法使用ExcelFile()将Excel文件加载到数据框中。 我input了pandas,xlrd和openpyxl。 我正在使用spyder进行交互式数据分析。 我是pandas和python的新手,所以我会教一个初学者可以理解的答案。 有人可以帮我吗?
>>> 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'
问题在于这一行:
>>> xls = ExcelFile('C:\RWFC\test.xls')
落后的斜线有特殊的意义。 例如,普通string中的字符“\ 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
确实有特殊的意义。 要解决这个问题,你可以使用“原始string”,并在string前加上“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'
无论哪种方式应该工作。
我有一个类似的问题。 我这样解决了这个问题:
path = r"Drive:\path\to\your\file.extension" workbook = xlrd.open_workbook(path) ##assuming you have imported xlrd already
希望这可以帮助。 🙂