sometimesiwritecode
sometimesiwritecode

Reputation: 3223

How do I append two lists of rows into one new row in python?

I have two two csvs with many columns in each. I am looping through the rows in each and would like to combine the rows as i go into a third csv that has the columns of both. so far this is the only way i can do it:

ee = csv.reader(open("ab.csv"), delimiter=",")
cc = csv.reader(open("cd.csv"), delimiter=",")

ofilePosts = open('complete.csv', 'ab')
writerPosts = csv.writer(ofilePosts, delimiter=',')

for e in ee:
    for c in cc:
         complete.writerow(e[0], e[1], e[2]...................

This takes along time to manually write out e[x] for the number of rows in x.

How can i just do something like this without getting a run time crash:

complete.writerow([e+c])

Upvotes: 1

Views: 1279

Answers (2)

Dogan Askan
Dogan Askan

Reputation: 1238

Use pandas, marge them by index so the missing rows from the file with fewer records will be filled by NA.

import pandas as pd
ee = pd.read_csv('ab.csv')
cc = pd.read_csv('cd.csv')

merged = pd.concat([ee, cc], axis=1) # merge by index
merged.to_csv('complete.csv') # to dump to a csv
print merged

Upvotes: 1

PYA
PYA

Reputation: 8636

Read the data from file1 and file2 into a list and then append them like so:

l =["row1","row2"] #list1
ll = ["row1","row2"] #list2

a = [[l[x],ll[x]] for x in range(len(l))]

print(a) # [['row1', 'row1'], ['row2', 'row2']]

This will only work properly if number of rows is same.

Upvotes: 0

Related Questions