我正在尝试使用熊猫在pycharm中读取excel文件。我成功安装了软件包。我的问题是,除了名称之外,我还尝试使用文件位置,我尝试了很多操作,如下所示:
import pandas as pd
fileLocation = "C:\\Users\\GTS\\Desktop\\Network Interdiction Problem\\Manuscript\\Interdiction_Data.xlsx"
fileName = 'Interdiction_Data.xlsx'
data = pd.read_excel('fileLocation'+'fileName')
但是我仍然收到以下错误
Traceback (most recent call last):
File "C:/Users/GTS/PycharmProjects/Reliability1/Reliability1.py", line 4, in <module>
data = pd.read_excel('fileLocation'+'fileName')
File "C:\Users\GTS\PycharmProjects\Reliability1\venv\lib\site-packages\pandas\io\excel\_base.py", line 304, in read_excel
io = ExcelFile(io, engine=engine)
File "C:\Users\GTS\PycharmProjects\Reliability1\venv\lib\site-packages\pandas\io\excel\_base.py", line 824, in __init__
self._reader = self._engines[engine](self._io)
File "C:\Users\GTS\PycharmProjects\Reliability1\venv\lib\site-packages\pandas\io\excel\_xlrd.py", line 21, in __init__
super().__init__(filepath_or_buffer)
File "C:\Users\GTS\PycharmProjects\Reliability1\venv\lib\site-packages\pandas\io\excel\_base.py", line 353, in __init__
self.book = self.load_workbook(filepath_or_buffer)
File "C:\Users\GTS\PycharmProjects\Reliability1\venv\lib\site-packages\pandas\io\excel\_xlrd.py", line 36, in load_workbook
return open_workbook(filepath_or_buffer)
File "C:\Users\GTS\PycharmProjects\Reliability1\venv\lib\site-packages\xlrd\__init__.py", line 111, in open_workbook
with open(filename, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'fileLocationfileName'
任何想法?
提前感谢
您的fileLocation
变量包括文件名。阅读fileLocation + fileName
本质上是阅读
C:\\Users\\GTS\\Desktop\\Network Interdiction Problem\\Manuscript\\Interdiction_Data.xlsxInterdiction_Data.xlsx
另一个问题是,在调用pd.read_excel()
时,变量名周围会带有引号,这意味着您正在向函数传递字符串。
尝试:
data = pd.read_excel(fileLocation)
我在您的代码中看到一些问题...首先,让我们从pd.read_excel()文档开始:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
它说如果文件保存在当前工作目录中,只需将文件名传递给函数即可。
import pandas as pd
fileName = 'Interdiction_Data.xlsx'
data = pd.read_excel(fileName) # notice that when we call an object, we didn't use quotation marks.
但是,如果您的文件不在当前目录中,则只需将路径传递到该文件,或者将其称为“ filelocation”。
import pandas as pd
fileLocation = "C:\\Users\\GTS\\Desktop\\Network Interdiction Problem\\Manuscript\\Interdiction_Data.xlsx"
data = pd.read_excel(fileLocation) # notice that when we call an object, we didn't use quotation marks.
提示:为避免某些错误或文件路径或目录名称出现问题,请尽量不要使用空格,因此请分开两个单词...
希望您能解决您的问题。