简体   繁体   中英

Writing header to a csv file in python

I have this csv file ( file.csv) :

1,4.00,B
1,8.00,C
2,5.00,"B,C"
2,6.50,"C,D"
3,4.00,B
3,8.00,"B,D"

I would like to read this file in python and then write a header( ID, COST, NAME) to this csv file in python. So that it looks like this.

ID,COST,NAME
1,4.00,B
1,8.00,C
2,5.00,"B,C"
2,6.50,"C,D"
3,4.00,B
3,8.00,"B,D" 

How can I do this ?

What about this?

headers = ["ID", "COST", "NAME"]
rows = [(1, 4.00,"B"),
        (1, 8.00,"C")]
with open(name.csv','w') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(headers)
    f_csv.writerows(rows)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM