Reputation: 121
I'm writting a simple code to write a CSV file using python, here's my code
import csv
#Header of rows
HYear=[' ','Year','2017']
HMonth=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
HData=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18', '19','20','21','22','23','24','25','26','27','28','29','30','31']
#write csv
with open('test.csv', 'w') as csvfile:
fieldnames = ['{0}','{1}'.format(HYear[0],HYear[1])]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'{0}': ' ' , '{1}': 'MONTH' .format(HYear[0],HYear[1])})
writer.writerow({'{0}': 'STATION', '{1}': 'CODE' .format(HYear[0],HYear[1])})
I tried first using '%s'%Var and now im using '{0}'.format(Var) due to some list, tuples error... the problem is that it will still not read or work; the code above is just for testing, at the end I'm doing a for to generate a calendar-like csv.
#Error
File "test.py", line 15, in <module>
writer.writerow({'{0}': ' ' , '{1}': 'MONTH' .format(HYear[0],HYear[1])})
File "/usr/lib64/python2.7/csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "/usr/lib64/python2.7/csv.py", line 144, in _dict_to_list
", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames: {1}
Thanks in advance
Upvotes: 0
Views: 426
Reputation: 3100
fieldnames = HYear[:2]
...
writer.writerow({HYear[0]: ' ' , HYear[1]: 'MONTH'})
writer.writerow({HYear[0]: 'STATION', HYear[1]: 'CODE' })
Or more pythonistic:
writer.writerow(dict(zip(fieldnames, (' ', 'MONTH'))))
writer.writerow(dict(zip(fieldnames, ('STATION', 'CODE'))))
Upvotes: 3