简体   繁体   中英

Python i would like to know how to writerow with a for loop (DictWriter)

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})

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]})

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM