0

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?

Pa Met
  • 1
  • 1
  • Are you looking to flatten this list of 3 lists into one row of 9 columns? – abarnert May 03 '18 at 05:27
  • 1
    can you please make a matrix to show what you want ? – Hari_pb May 03 '18 at 05:27
  • If that's all you want, it's a duplicate of [this question](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python), which has a great answer. – abarnert May 03 '18 at 05:28
  • Thanks guys. As it turned out everything already works alright with the code above. My excel settings had to be changed. That was the reason why the different elements were not in seperated columns – Pa Met May 03 '18 at 06:07

2 Answers2

1

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)
Fishy
  • 26
  • 5
0

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)
Martin Evans
  • 45,791
  • 17
  • 81
  • 97