2016-09-30 78 views
0

我想用sheet1和sheet2追加很多excel文件。 我写了下面的代码excel文件与python中的表合并

import os 
import pandas as pd 

files = os.listdir("C:/Python27/files") 
files 
df = pd.DataFrame() 
for f in files: 
    data = pd.read_excel(f, 'Sheet1', 'Sheet2') 
    df = df.append(data) 

文件的示例名称:总计2014年4月,道达尔2014年8月

以下是错误:

Traceback (most recent call last): 
    File "C:/Python27/filemerge2.py", line 10, in <module> 
    data = pd.read_excel(f, 'Sheet1', 'Sheet2') 
    File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 170, in read_excel 
    io = ExcelFile(io, engine=engine) 
    File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 227, in __init__ 
    self.book = xlrd.open_workbook(io) 
    File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 395, in open_workbook 
    with open(filename, "rb") as f: 
IOError: [Errno 2] No such file or directory: 'Total Apr 2014.xls' 

这将是巨大的,如果有人可以帮助我解决这个错误

回答

0

Python os.listdir将返回一个列表,其中包含relati已经在给定目录内命名了文件。如果您从"C:/Python27/files"(或您的xls文件所在的文件夹)以外的文件夹运行脚本,则需要为其提供read_excel()函数(或您调用的任何文件管理函数)所需文件的完整路径。

使你的脚本工作,只是基本的文件夹添加到文件名,它应该工作:

import os 
import pandas as pd 

folder = "C:/Python27/files" 
files = os.listdir(folder) 
files 
df = pd.DataFrame() 
for f in files: 
    data = pd.read_excel(folder + '/' + f, 'Sheet1', 'Sheet2') 
    df = df.append(data) 

注意os.listdir将返回内部folder所有文件和目录,无论其类型。请务必尝试与read_excel()打开它之前进行一些文件类型检查(或者只使用一个try-except块周围的for循环依赖于该呼叫的内容)。

+0

感谢@csantos。我现在有了一个新的错误。 'Traceback(last recent call last): 文件“C:/Python27/filemerge2.py”,第9行,在 data = pd.read_excel(folder +'/'+ f,'Sheet1','Sheet2') 文件“C:\ Python27 \ lib \ site-packages \ pandas \ io \ excel.py”,第178行,在read_excel中为 squeeze = squeeze,** kwds) 文件“C:\ Python27 \ lib \ site-packages \ pandas \ io \ excel.py“,第434行,在_parse_excel中 data [header] = _trim_excel_header(data [header]) TypeError:列表索引必须是整数,而不是str' – venkatsai

+0

来自[pandas documentation](http: /pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html),看起来'read_excel'的第三个参数必须是整数或整数列表,但是您传递的是'Sheet2 '而是。 – csantos