如何在循环中传递csv的标头

时间:2019-01-30 08:40:56

标签: python python-3.x csv

我想循环创建一个csv文件。但是,当我这样做时,它也会同时写标题部分。如何只写一次标题部分?

fieldnames=['numbers']
for i in range(0,100):
    with open('numbers.csv','a',newline='') as csvfile:
        writer=csv.Dictwriter(csvfile,fieldnames=fieldnames,lineterminator='\n')
        writer.writeheader()
        writer.writerow({'numbers':i})

1 个答案:

答案 0 :(得分:3)

非常简单:将这部分移出循环(似乎很明显...)。您绝对不想在每次迭代中都重新打开文件(打开文件-关闭FWIW绝非免费):

fieldnames=['numbers']
with open('numbers.csv','a',newline='') as csvfile:
    writer = csv.Dictwriter(csvfile,fieldnames=fieldnames,lineterminator='\n')
    writer.writeheader()
    for i in range(100):
        writer.writerow({'numbers':i})