Created
July 10, 2015 18:24
-
-
Save simonw/0798399b443b32d2de2b to your computer and use it in GitHub Desktop.
Here's how to use Python to output an Excel-compatible CSV (actually TSV) file from a command-line script. You can then use this pattern: "python csv_example.py | pbcopy" to copy the output to your clipboard, then just focus on a cell in Excel or Google Sheets and hit "paste" to copy the data into a bunch of cells.
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, sys | |
def fetch_data(): | |
# Returning some example data - hit a JSON API or something here | |
return [{ | |
"name": "Name 1", | |
"age": 32, | |
"description": "Look, we can use commas and\ttabs & stuff in here!", | |
}, { | |
"name": "Name 2", | |
"age": 28, | |
"description": "More of the same...", | |
}] | |
def make_csv_rows(dicts, keys): | |
rows = [] | |
rows.append(keys) | |
for item in dicts: | |
rows.append([item[key] for key in keys]) | |
return rows | |
if __name__ == '__main__': | |
dicts = fetch_data() | |
rows = make_csv_rows(dicts, ('name', 'age', 'description')) | |
# output csv to stdout | |
w = csv.writer(sys.stdout, csv.excel_tab) | |
w.writerows(rows) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment