Append a Header for CSV file?

后端 未结 6 662
后悔当初
后悔当初 2020-12-25 07:59

I am trying to add a header to my CSV file.

I am importing data from a .csv file which has two columns of data, each containing float numbers. Example:



        
6条回答
  •  时光说笑
    2020-12-25 08:41

    One way is to read all the data in, then overwrite the file with the header and write the data out again. This might not be practical with a large CSV file:

    #!python3
    import csv
    with open('file.csv',newline='') as f:
        r = csv.reader(f)
        data = [line for line in r]
    with open('file.csv','w',newline='') as f:
        w = csv.writer(f)
        w.writerow(['ColA','ColB'])
        w.writerows(data)
    

提交回复
热议问题