Created
August 30, 2013 22:35
-
-
Save edhiley/6394948 to your computer and use it in GitHub Desktop.
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
{ | |
"metadata": { | |
"name": "CSV fun" | |
}, | |
"nbformat": 3, | |
"nbformat_minor": 0, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "Prepare writer with known headers" | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": "import sys, csv\nwriter = csv.DictWriter(sys.stdout, [\"Column one\",\"Column two\"])", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 1 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "Insert header and data" | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": "data = [\n {\"Column one\": \"row 1\", \"Column two\": \"row 1\"}, \n {\"Column one\": \"row 2\", \"Column two\": \"row 2\"}\n]\nwriter.writeheader()\nwriter.writerows(data)", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": "Column one,Column two\r\nrow 1,row 1\r\nrow 2,row 2\r\n" | |
} | |
], | |
"prompt_number": 2 | |
}, | |
{ | |
"cell_type": "raw", | |
"metadata": {}, | |
"source": "Or use generators to provide formatters if required" | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": "def myformatter(i):\n return i**2", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 3 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": "writer.writeheader()\nwriter.writerows(({\"Column one\": myformatter(x), \"Column two\": x} for x in range(1, 10)))", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": "Column one,Column two\r\n1,1\r\n4,2\r\n9,3\r\n16,4\r\n25,5\r\n36,6\r\n49,7\r\n64,8\r\n81,9\r\n" | |
} | |
], | |
"prompt_number": 4 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": "", | |
"language": "python", | |
"metadata": {}, | |
"outputs": [] | |
} | |
], | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment