2

I have a list of lists example: list_of_lists = [['name1', 'number1', 'comment1'], ['name2', 'number2', 'comment2'], ['name3', 'number3', 'comment3']]

I want to write them into a csv file that should look like this:

NAME  NUMBER  COMMENT
name1 number1 comment1
name2 number2 comment2
name3 number3 comment3

I tried:

rows = zip(*list_of_lists)
import csv
with open('new.csv', "w") as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

But that writes it as:

name1    name2   name3
number1  number2 comment2
comment1 number3 comment3

If I use rows = zip(list_of_lists) instead of rows = zip(*list_of_lists), I get all data as string in csv:

"name1, number1, comment1"
"name2, number2, comment2"
"name3, number3, comment3"

How do I get the desired result?

1
  • Why do you want to use zip() at all ? Your data are already in the right format. Commented Dec 13, 2018 at 13:06

1 Answer 1

4

You can use them directly.

Ex:

import csv

list_of_lists = [['name1', 'number1', 'comment1'], ['name2', 'number2', 'comment2'], ['name3', 'number3', 'comment3']]

with open(filename, "w") as f:
    writer = csv.writer(f)
    writer.writerow(["NAME", "NUMBER", "COMMENT"])
    for row in list_of_lists:
        writer.writerow(row)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.