John M
John M

Reputation: 3

append several rows to csv

I've hopefully got a pretty easy one for you all! I need to append several rows to a csv. Here's the general structure:

f=((np.array(i)).tolist())
g=((np.array(j)).tolist())
h=((np.array(k)).tolist())

with open('output.csv','a') as z:
    z.write(",".join(map(str,f)))

This is great for a single row of data! However, I have several rows to add. If I try doing this, all of the data is appended as one row!

f=((np.array(i)).tolist())
g=((np.array(j)).tolist())
h=((np.array(k)).tolist())

with open('output.csv','a') as f:
    z.write(",".join(map(str,f)))
    z.write(",".join(map(str,g)))
    z.write(",".join(map(str,h)))

My question boils down to: how do I append several lists to my csv as separate rows? Can I slap a \n somewhere?

Upvotes: 0

Views: 66

Answers (1)

cwallenpoole
cwallenpoole

Reputation: 82078

You shouldn't be trying to roll your own CSV writer. You should use the csv module's CSVWriter object:

import csv

with open('output.csv', 'w') as store:
    writer = csv.writer(store)
    for row in [i, j, k]:
        writer.writerow((np.array(row)).tolist())

Upvotes: 3

Related Questions