python 将多个CSV文件合成一个

1、当csv文件不含表头(即纯数据,没有列名称)

import pandas as pd
from tqdm import tqdm  # 进度条模块

from glob import glob
lst_file = glob("D:\\test\\*.csv")  

for in_file in tqdm(lst_file):  # 对迭代器添加进度条显示

    df = pd.read_csv(in_file) 
    df_data = pd.DataFrame(df)  
       
    df_data.to_csv("D:\\test.csv",index = False,mode='a')
    
# 插入表头
df = pd.read_csv('D:\\test.csv',header=None,names=['name','grade','class','age','score']) 
df.to_csv('D:\\test.csv',index=False)

2、当csv文件含表头(即有列名称)

import pandas as pd
from tqdm import tqdm  # 进度条模块

from glob import glob
lst_file = glob("D:\\test\\*.csv")  

data = pd.Dataframe()
for in_file in tqdm(lst_file):  # 对迭代器添加进度条显示

    df = pd.read_csv(in_file) 
    df_data = pd.DataFrame(df)  
    data = pd.concat([data,df_data])   
data.to_csv("D:\\test.csv",index = False)

你可能感兴趣的:(Python,python)