Last active
May 30, 2022 03:19
-
-
Save nwandabridges/58d26d419631acd6dcec4af1825c28df to your computer and use it in GitHub Desktop.
Create a CSV that is properly formatted for MS Excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
arbitrary_list_of_dictionaries = [{'hello': 'world'}, {'hello': 'you'}] | |
arbitrary_output_path = 'output.csv' | |
# Use the keys from the first dictionary as field names in CSV | |
field_names = [key for key in arbitrary_list_of_dictionaries[0].keys()] | |
# Note: The 'encoding' argument is important. It adds a BOM (byte order mark) | |
# to the beginning of the file. | |
with open(arbitrary_output_path, 'w', encoding='utf-8-sig') as output_file: | |
# Note: The 'dialect' argument ensures that the outputted CSV matches | |
# Excel's specifications | |
writer = csv.DictWriter(file, fieldnames=field_names, dialect=csv.excel) | |
writer.writeheader() | |
for dictionary in arbitrary_list_of_dictionaries: | |
writer.writerow(dictionary) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment