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
解决方案
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.