samedi 5 avril 2014

CSV to python list of dicts?


Vote count:

0




I looked through the questions already posted and my problems isn't quite solved. Newbie to Python! I think this should be fairly straight forward but I am getting tripped up with the variations. Hoping that after getting walked through this one file, then I can upload and parse the rest. Thanks!!!


What I am trying to do:



  • File is open states data (and other files in dropbox): ca_bills.csv

  • Convert .csv to python: I think it should be converted to a python list of dicts

  • Use the headers in the file as keys within dicts


I tried this but it didn't do what I wanted + I wonder if there is way to pull the fieldname from the headers of each file



def csv_dict_writer(fp, fieldnames, data):
with open(fp, "wb") as out_file:
writer = csv.DictWriter(out_file, deliminter=',', fieldnames=fieldnames)
writer.writeheader()
for row in data:
writer.writerow(row)


I also did this but this only prints and doesn't write to a file:



with open('ca_bills.csv') as output_file:
reader = csv.reader(output_file)
for row in reader:
print row


Thanks so much! This may be similar to other question but really couldn't extract what I needed. Appreciate your insights.



asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire