Below is code that takes a list of dictionaries and writes them to a CSV file.
import csv
def createBaselineCSV(baselineDictionaryList, name):
toCSV = baselineDictionaryList
keys = toCSV[0].keys()
print(keys)
with open(name, 'w') as output_file:
dict_writer = csv.DictWriter(output_file, fieldnames=keys)
dict_writer.writeheader()
dict_writer.writerows(toCSV)
contacts = [{'Name':'John Smith', 'Email':'[email protected]', 'Phone':'888-888-8888'}, {'Name':'Keith Stone', 'Email':'[email protected]', 'Phone':'000-000-000'}]
createBaselineCSV(contacts, 'contacts.csv')
However the columns of the created CSV file do not maintain a consistent format each time a new spreadsheet is created. So one time it might create a CSV that looks like:
Name, Email, Phone
John Smith, [email protected], 888-888-8888
Keith Stone, [email protected], 000-000-0000
And the next time it might make a CSV that looks like this:
Email, Phone, Name
[email protected], 888-888-8888, John Smith
[email protected], 000-000-0000, Keith Stone
Is there a good way to make sure that the CSV is created with the column cells in a fixed position each time? For example Column A is always 'Name', Column B is always 'Email', and Column C is always 'Phone'.
I am guessing that accomplishing this will mean calling createBaselineCSV on a different data type other than a list of dictionaries(because dictionaries don't maintain a specified order), rather than reformatting the code within the function. What would be the best approach?