{ "metadata": { "name": "export" }, "nbformat": 2, "worksheets": [ { "cells": [ { "cell_type": "markdown", "source": [ "Exporting data from Python", "==========================", "Delimited text", "--------------", "Exporting data from Python into delimited text files can be accomplished using a variety of modules. Here we'll focus on csv, numpy, and pandas." ] }, { "cell_type": "markdown", "source": [ "### CSV", "To export using the csv module we:", "", "1. Open the output file", "2. Create a write object", "3. Write the rows to the data file (writerows() will write all of the lines at once, you can also use writerow() in a loop to write them one at a time)", "4. Close the output file" ] }, { "cell_type": "code", "collapsed": true, "input": [ "import csv", "", "data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]", "", "output_file = open('./data/examp_output.txt', 'w')", "datawriter = csv.writer(output_file)", "datawriter.writerows(data)", "output_file.close()" ], "language": "python", "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "source": [ "### Numpy", "", "In Numpy the export is just a single line use savetxt()" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np", "", "data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]", "", "np.savetxt('./data/examp_output.txt', data, delimiter = ',')" ], "language": "python", "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "source": [ "### Pandas", "Using Pandas, the data frame has a method to_csv that allows writing to delimited text. The default in Pandas is to include column names and the index and so the output is somewhat different for this example than the other approaches." ] }, { "cell_type": "code", "collapsed": true, "input": [ "import pandas as pd", "", "data = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])", "data.to_csv('./data/examp_output.txt')" ], "language": "python", "outputs": [], "prompt_number": 3 } ] } ] }