Append a Header for CSV file?

后端 未结 6 700
后悔当初
后悔当初 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:52

    In this case, You don't need the CSV module. You need the fileinput module as it allows in-place editing:

    import fileinput
    
    for line in fileinput.input(files=['mycsvfile.csv'], inplace=True):
        if fileinput.isfirstline():
            print 'ColA,ColB'
        print line,
    

    In the above code, the print statement will print to the file because of the inplace=True parameter.

提交回复
热议问题