简体   繁体   English

Python我想知道如何使用for循环编写(DictWriter)

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

I am trying to write csv file with DictWriter . 我正在尝试用DictWriter编写csv文件。 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. 您正在for循环的每次迭代中编写相同的变量。 If my_list is a list of dictionaries, the code should be: 如果my_list是字典列表,则代码应为:

for i in my_list:
    w.writerow({"Code": i['code'], "Hight": i['hight'], "Country": i['country']})

If my_list is a list of lists, 如果my_list是列表列表,

for i in my_list:
    w.writerow({"Code": i[0], "Hight": i[1], "Country": i[2]})

This might help you 这可能对你有帮助

import csv 导入csv

nms = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]] nms = [[1,2,3,4,5,6],[7,8,9,10,11,12]]

f = open('numbers2.csv', 'w') f = open('numbers2.csv','w')

with f: 用f:

writer = csv.writer(f)

for row in nms:
    writer.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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