Writing header to a csv file in python
我有这个csv文件(file.csv):
1 2 3 4 5 6 | 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" |
我想用python读取这个文件,然后在python中写一个头文件(id、cost、name)到这个csv文件。所以看起来像这样。
1 2 3 4 5 6 7 | 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" |
我该怎么做?
这个怎么样?
1 2 3 4 5 6 7 | 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) |