导入excel文件错误python pandas

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15681802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:44:42  来源:igfitidea点击:

import excel file error python pandas

pythonexcelpandasspyder

提问by jonas

I have trouble loading excel files into a dataframe using ExcelFile(). I have imported pandas,xlrd and openpyxl. I am using spyder for interactive data analysis. I'm new to pandas and python, so I would appriciate an answer that is understandable for a beginner. Could someone help me?

我无法使用 ExcelFile() 将 excel 文件加载到数据框中。我已经导入了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'

回答by DSM

The problem is in this line:

问题出在这一行:

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

The backward slash has a special meaning. For example, the character "\t" in a normal string is the tab character:

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

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

That's why in your error message:

这就是为什么在您的错误消息中:

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

You see a double slash in front of the R-- \Rdoesn't have any special meaning, and so it knew you meant one "real" slash:

您看到R--前面的双斜线\R没有任何特殊含义,因此它知道您的意思是“真正的”斜线:

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

but \tdoes have a special meaning. To solve this problem you can either use a "raw string", and add "r" before the string literal:

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

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

or, you can simply use forward slashes instead -- which Windows supports -- and avoid all the trouble:

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

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

Either way should work.

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

回答by Debadatta Meher

I was having a similar problem. I resolved the issue this way:

我遇到了类似的问题。我这样解决了这个问题:

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

Hope this helps. :)

希望这可以帮助。:)