-
-
Save gregorynicholas/1d0cbf3e603075ad44905bd9390e1761 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