Lara19
Lara19

Reputation: 699

Python: write multiple lists to multiple rows in csv

At the moment, I know how to write a list to one row in csv, but when there're multiple rows, they are still written in one row. What I would like to do is write the first list in the first row of csv, and the second list to the second row.

Code:

for i in range(10):
    final=[i*1, i*2, i*3]
    with open ('0514test.csv', 'a') as file:
        file.write(','.join(str(i) for i in kk))

Upvotes: 0

Views: 661

Answers (2)

Benoit Lacherez
Benoit Lacherez

Reputation: 514

The csv module from standard library provides objects to read and write CSV files. In your case, you could do:

import csv
for i in range(10):
    final = [i*1, i*2, i*3]
    with open("0514test.csv", "a", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(final)

Using this module is often safer in real life situations because it takes care of all the CSV machinery (adding delimiters like " or ', managing the cases in which your separator is also present in your data etc.)

Upvotes: 0

MaKiPL
MaKiPL

Reputation: 1200

You may want to add linebreak to every ending of row. You can do so by typing for example:

file.write('\n')

Upvotes: 1

Related Questions