Skip to content

Instantly share code, notes, and snippets.

@simonw
Created July 10, 2015 18:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simonw/0798399b443b32d2de2b to your computer and use it in GitHub Desktop.
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.
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