读取多个csv文件并将其写入另一个csv文件

时间:2014-05-27 11:34:18

标签: python csv pandas

我有这段代码

import pandas as p
import csv
df = p.read_csv('interview1.csv')  
df2 = df[['Participant', 'Translation']]    # selects two of the columns in your file
df2.to_csv('out.csv')

如何阅读多个文件,然后写入' out.csv'。所以基本上,我没有阅读面试1,而是阅读面试2,面试3面试7以及out.csv

2 个答案:

答案 0 :(得分:3)

只需在附加模式下打开输出文件:

import pandas as p
import csv 
csv_list=['interview1.csv', 'interview2.csv', ...]
for itw in csv_list:
    df = p.read_csv(itw)
    df.to_csv('out.csv', mode='a')

答案 1 :(得分:1)

使用此方法从文件夹中读取所有.CSV数据并将其组合在一起

import pandas as pd
import glob
import os
path = r'file path'                   
all_files = glob.glob(os.path.join(path, "*.csv"))     

df_from_each_file = (pd.read_csv(f) for f in all_files)
concatenated_df   = pd.concat(df_from_each_file, ignore_index=True)
concatenated_df.to_csv("combined-data_new.csv")