美文网首页
多个excel文件合并到同一个文件os.walk()

多个excel文件合并到同一个文件os.walk()

作者: 弦好想断 | 来源:发表于2020-07-28 17:52 被阅读0次
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) 

    top :是你所要遍历的目录的地址, 返回的是一个三元组 (dirpath, dirnames, filenames) 

    topdown :可选,True则优先遍历 top 文件夹,与top 文件夹中每一个子目录;否则优先遍历 top 的子目录(默认为开启)。

    onerror :可选,需要一个 callable 对象,当 walk 需要异常时,会调用

    followlinks :可选,如果为 True,则会遍历目录下的快捷方式(linux 下是软连接 symbolic link )实际所指的目录(默认关闭),如果为 False,则优先遍历 top 的子目录

# 多个excel文件合并到同一个文件
import os
import pandas as pd

# 将文件读取出来放一个列表里面

# 新建列表,存放文件名
file_list = []
# 新建列表存放每个文件数据(依次读取多个相同结构的Excel文件并创建DataFrame)
dfs = []

pwd = r'C:\Users\D1M\Desktop\7月24家店铺近30天会员数据'  # 获取文件目录
for root,dirs,files in os.walk(pwd):  # 第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
    for file in files:
        file_path = os.path.join(root,file)
        file_list.append(file_path) # 使用os.path.join(dirpath, name)得到全路径
        df = pd.read_excel(file_path) # 将excel转换成DataFrame
        dfs.append(df)
dfs

# # 将多个DataFrame合并为一个
# df = pd.concat(dfs)
# # 写入excel文件,不包含索引数据
# df.to_excel('test\\result.xls', index=False)

相关文章

网友评论

      本文标题:多个excel文件合并到同一个文件os.walk()

      本文链接:https://www.haomeiwen.com/subject/mrhqrktx.html