learningToCode54321
learningToCode54321

Reputation: 67

Use Python CSV module to write to csv keeping the columns in the same order each time

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?

Upvotes: 2

Views: 215

Answers (2)

OldGeeksGuide
OldGeeksGuide

Reputation: 2918

pandas makes this very easy:

import pandas as pd

contacts = [{'Name':'John Smith', 'Email':'[email protected]', 'Phone':'888-888-8888'}, {'Name':'Keith Stone', 'Email':'[email protected]', 'Phone':'000-000-000'}]
df = pd.DataFrame(contacts)
df[['Name', 'Email', 'Phone']].to_csv('contacts.csv', index=False)

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36043

Your problem is fieldnames=keys where keys comes from a dict which has no order. Just set fieldnames=['Name', 'Email', 'Phone'] or whatever you want it to be. You can continue using dicts and DictWriter.

Upvotes: 4

Related Questions