Pa Met
Pa Met

Reputation: 1

How to write each element of a list into a seperate field in a csv file?

I want to write a list of lists into a csv file. Each element of a list should go into a new column and each list should have its own row. I can`t figure out how to insert each element of a list to a new column. My code looks like this:

example_list = [[1,2,3], [4,5,6], [7,8,9]]

with open('example.csv', 'w') as f:
    writer = csv.writer(f)

    for line in example_list:
        writer.writerow(line)

But this will give me a file with each list in a single column. Can anybody give me a hint how to seperate the list elements?

Upvotes: 0

Views: 1610

Answers (2)

Martin Evans
Martin Evans

Reputation: 46759

The code you have should already create a correct CSV file. You should though add newline='' to your open() parameters if you are using Python 3.x with a CSV writer.

Also note, as you are writing a list of lists, you could also just do this as follows:

import csv

example_list = [[1,2,3], [4,5,6], [7,8,9]]

with open('example.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(example_list)

Upvotes: 0

Fishy
Fishy

Reputation: 26

As written, your code gives me the following csv file:

1,2,3
4,5,6
7,8,9

So it's already been separated into columns. If you wanted to separate them by tabs (or spaces) instead of commas, try the following:

import csv
example_list = [[1,2,3], [4,5,6], [7,8,9]]
with open('example.csv', 'w') as f:
    writer = csv.writer(f, delimiter='\t')
    for line in example_list:
        writer.writerow(line)

Upvotes: 1

Related Questions