2

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 ?

2
  • You could use open, readlines, and writelines Commented Mar 18, 2014 at 6:51
  • Do you really have a problem with this? What stops you from simply writing "ID,COST,NAME" as the first time to the new file? Commented Mar 18, 2014 at 6:56

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.