In python 3 things are a little different, but way simpler and less error prone. It's a good idea to tell the CSV your file should be opened with utf8
encoding, as it makes that data more portable to others (assuming you aren't using a more restrictive encoding, like latin1
)
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
with open('people.csv', 'w', encoding='utf8', newline='') as output_file:
fc = csv.DictWriter(output_file,
fieldnames=toCSV[0].keys(),
)
fc.writeheader()
fc.writerows(toCSV)
csv
in python 3 needs the newline=''
parameter, otherwise you get blank lines in your CSV when opening in excel/opencalc.Alternatively: I prefer use to the csv handler in the pandas
module. I find it is more tolerant of encoding issues, and pandas will automatically convert string numbers in CSVs into the correct type (int,float,etc) when loading the file.
import pandas
dataframe = pandas.read_csv(filepath)
list_of_dictionaries = dataframe.to_dict('records')
dataframe.to_csv(filepath)
Note:
utf8
in python3, and figure out headers too.dataframe.to_dict('records')
csv
module, you need to feed it an OrderedDict
or they'll appear in a random order (if working in python < 3.5). See: Preserving column order in Python Pandas DataFrame for more.