批量合并同类型文件

需求简述:电脑上下载了大量的以.xlsx文件,需要将.xlsx合并在一张.xlsx中,如果手动去合并太浪费时间而且容易出错

当前存在的问题:
1、xlsx存放在同一个文件夹,但文件夹中也存在其他类型的文件,比如.txt,以及pdf,而需求是只合并xlsx类型的文件
2、各个xlsx表头可能会不一致

import xlrd
import pandas as pd
import os

`

``python

指定存放文件的地址,也就是要去读哪个文件夹下的文件,这是一个绝对路径

dir_str=r’D:\米家业务\暖风机\电商平台需求调研\京东商品评价’



```python
## 获取指定文件夹下所有csv文件名称并传送给file_name_list,用一个list去装所有的文件
file_name_list=os.listdir(dir_str)
## 遍历出该文件夹下的所有csv格式的文件,使用for循环
file_dir_list=[os.path.join(dir_str,x) for x in file_name_list]
print(file_dir_list) ### 全部去读取到了
### 定义DataFrame类型的变量df用来存放获取的所有数据
df=pd.DataFrame()
## for 循环遍历读取每个xlsx里面的数据
for i in file_name_list:
    if(i[-9:]=='好中差评.xlsx'):   ## 筛选只读取xlsx结尾的文件,list的切片方法
        EXCEL1=pd.read_excel(file_dir_list[i])
        # concat 方法合并多个文件的数据
        df=pd.concat(df,EXCEL1)

运行结果出错了

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-82-1d65c5381c60> in <module>
      2 for i in file_name_list:
      3     if(i[-9:]=='好中差评.xlsx'):   ## 筛选只读取xlsx结尾的文件,list的切片方法
----> 4         EXCEL1=pd.read_excel(file_dir_list[i])
      5         # concat 方法合并多个文件的数据
      6         df=pd.concat(df,EXCEL1)

TypeError: list indices must be integers or slices, not st

猜你喜欢

转载自blog.csdn.net/weixin_42961082/article/details/109740041