Reputation: 51
I am trying to write csv file with DictWriter . So far i have created a list and a loop but it only writes the last row of the list , number of times how many items are in the list. This is my code:
fieldnames = ['Code', 'Hight', 'Country']
with open('write.csv', 'w',newline="") as f:
w = csv.DictWriter(f,fieldnames=fieldnames,delimiter = "\t")
w.writeheader()
for i in my_list:
w.writerow({"Code":code,"Hight":hight,"Country":country})
Upvotes: 0
Views: 794
Reputation: 23
This might help you
import csv
nms = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
f = open('numbers2.csv', 'w')
with f:
writer = csv.writer(f)
for row in nms:
writer.writerow(row)
Upvotes: 0
Reputation: 11070
You are writing the same variable on each iteration of the for loop. If my_list
is a list of dictionaries, the code should be:
for i in my_list:
w.writerow({"Code": i['code'], "Hight": i['hight'], "Country": i['country']})
If my_list
is a list of lists,
for i in my_list:
w.writerow({"Code": i[0], "Hight": i[1], "Country": i[2]})
Upvotes: 1