Reputation: 33
I want to create a csv file in a loop. But when I do so, it also writes header part also. How can I write the header part only for a time?
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})
Upvotes: 0
Views: 222
Reputation: 77912
Quite simply: move this part out of the loop (seems obvious...). You DONT want to reopen the file in each iteration anyway (opening a file - and closing it FWIW - is far from free):
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})
Upvotes: 3