How to copy columns from several csv files into a single csv file with python? -


i have several 1 column csv files in directory named path , want merge these column in single files , store file out.csv in directory named repsim. here code:

suppose have list files , fin=files[0]

def ajouter (fin, files, out, path, repsim, delim=';'):     fic=os.path.join(path,fin)     open(fic, 'rb') fr:         print fic + " est overt"         tout=[]         in range(1, len(files)):             fil=files[i]             print fil + " en cours -------------"             f=os.path.join(path,fil)             open(f, 'rb') fi:                 fr_reader = csv.reader(fr, delimiter=delim)                 fi_reader = csv.reader(fi, delimiter=delim)                   row1, row2 in zip(fr_reader, fi_reader):                     row2.append(row1[-1])                     tout.append(row2)          fout=os.path.join(repsim,out)         open(fout, 'ab') output:              writer = csv.writer(output, delimiter=delim)             writer.writerows(tout) 

this code give me 2 columns file consisting of column of files[0] , column of last file in files.

while might interesting exercise you, there need re-invent wheel. straight-forward using e.g. pandas:

import pandas pd dataframes = [pd.read_csv(p) p in ("data1.csv", "data2.csv")] merged_dataframe = pd.concat(dataframes, axis=1) merged_dataframe.to_csv("merged.csv", index=false) 

input:

$ cat data1.csv  data1 b c d $ cat data2.csv  data2 p q r s 

output:

$ cat merged.csv  data1,data2 a,p b,q c,r d,s 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -