0

I have combined two lists using zip syntax. When I saved it in csv format, whole data are stayed in one cell of excell. what's that i want is: each element of zipped file should be stay on each row.

This is my code:

list_of_first_column=["banana","cat","brown"]
list_of_second_column=["fruit","animal","color"]

graph_zip_file=zip(list_of_first_column,list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(graph_zip_file)

what I want in csv format:

banana,fruit
cat,animal
brown,color
1
  • Replace writer.writerow(graph_zip_file) with writer.writerows(graph_zip_file). Commented Nov 14, 2017 at 13:58

1 Answer 1

1

You've got two ways of doing this, assuming that you're using the csv module. You can either use writer.writerows:

list_of_first_column = ["banana", "cat", "brown"]
list_of_second_column = ["fruit", "animal", "color"]

graph_zip_file = zip(list_of_first_column, list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerows(graph_zip_file)

Or, you can use writer.writerow and a for-loop:

list_of_first_column = ["banana", "cat", "brown"]
list_of_second_column = ["fruit", "animal", "color"]

graph_zip_file = zip(list_of_first_column, list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    for row in graph_zip_file
        writer.writerow(row)

They both should return the same thing, which is what you've indicated as your desired output.

I hope this proves useful.

Sign up to request clarification or add additional context in comments.

1 Comment

I changed writrow to writeros and it have worked. Thank a lot

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.