Pythonically add header to a csv file

前端 未结 3 1824
悲&欢浪女
悲&欢浪女 2020-11-29 01:04

I wrote a Python script merging two csv files, and now I want to add a header to the final csv. I tried following the suggestions reported here and I got the following error

3条回答
  •  天命终不由人
    2020-11-29 01:34

    You just add one additional row before you execute the loop. This row contains your CSV file header name.

    schema = ['a','b','c','b']
    row = 4
    generators = ['A','B','C','D']
    with open('test.csv','wb') as csvfile:    
         writer = csv.writer(csvfile, delimiter=delimiter)
    # Gives the header name row into csv
         writer.writerow([g for g in schema])   
    #Data add in csv file       
         for x in xrange(rows):
             writer.writerow([g() for g in generators])
    

提交回复
热议问题