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.


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
In [1]:
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)


In Numpy the export is just a single line use savetxt()

In [2]:
import numpy as np

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

np.savetxt('./data/examp_output.txt', data, delimiter = ',')


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.

In [3]:
import pandas as pd

data = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])