使用Pandas Python无法访问excel文件

嗨,我想通过几个Excel文件运行我的Python代码,并从每个文件中获取数据并保存到数据框架。 这是我的代码

import os import glob import pandas as pd path =r'C:\Users\user1\Desktop\test' files = os.listdir(path) files_xls = [f for f in files if f[-3:] == 'xls'] df = pd.DataFrame() for f in files_xls: filename, ext = os.path.splitext(f) data = pd.read_excel(f, filename) df = df.append(data) a = df.describe() print (a) 

我得到这个错误..我在工作的文件夹中的第一个文件是test.xls

 Traceback (most recent call last): File "test.py", line 20, in <module> data = pd.read_excel(f, filename) File "C:\Users\user1\AppData\Local\Programs\Python\Python35-32\lib\site- packages\pandas\io\excel.py", line 170, in read_excel io = ExcelFile(io, engine=engine) File "C:\Users\user1\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pandas\io\excel.py", line 227, in __init__ self.book = xlrd.open_workbook(io) File "C:\Users\user1\AppData\Local\Programs\Python\Python35-32\lib\site-packages\xlrd\__init__.py", line 395, in open_workbook with open(filename, "rb") as f: FileNotFoundError: [Errno 2] No such file or directory: 'test.xls' 

 import os import pandas as pd path =r'C:\Users\user1\Desktop\test' os.chdir(path) files = os.listdir(path) files_xls = [f for f in files if f[-3:] == 'xls'] df = pd.DataFrame() for f in files_xls: data = pd.read_excel(f) df = df.append(data) a = df.describe() print (a) 

文件未find,因为您正在调用对Excel文件的相对引用,并且Python脚本可能不与文件位于同一文件夹中。 因此,使用绝对引用,这是不符合被调用脚本的位置。 您可以通过使用os.path.join()将path连接到文件名来完成此操作:

 import os import pandas as pd path = r'C:\Users\user1\Desktop\test' files = os.listdir(path) files_xls = [f for f in files if f[-3:] == 'xls'] dfList = [] for f in files_xls: data = pd.read_excel(os.path.join(path, f)) dfList.append(data) df = pd.concat(dfList) 

或者,使用glob避免检查扩展名并检索文件的完整path:

 import glob import pandas as pd path = r'C:\Users\user1\Desktop\test' files_xls = glob.glob(path+'\*.xls') dfList = [] for f in files_xls: data = pd.read_excel(f) dfList.append(data) df = pd.concat(dfList)