user3134370
user3134370

Reputation:

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 ?

Upvotes: 2

Views: 1132

Answers (1)

barrios
barrios

Reputation: 1124

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)

Upvotes: 1

Related Questions