简体   繁体   中英

Reading multiple csv files and writing it to another csv file

I have this code

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')

How do i read multiple files and then write to 'out.csv'. So basically, instead of reading only interview1, i read interview2, interview3 to interview7 as well into the out.csv

Simply open the output file in append mode:

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')

Use this to read all.CSV data from a folder and combined it together

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM