How to read and write a table / matrix to file with python?

YamSMit picture YamSMit · Feb 8, 2013 · Viewed 43.3k times · Source

I'm trying to create a program that takes data and puts it in a 2 by 10 table of just numbers in a text file. Then the program needs to retrieve this information in later iterations. But I have no idea how to do this. I've been looking at numpty commands, regular file commands, and ways to try and make a table. But I can't seem to get any of this to work.

Here is an example of the table I am trying to make:

0    1    1    1    0    9    6    5
5    2    7    2    1    1    1    0

Then I would retrieve these values. What is a good way to do this?

Answer

Matt Luongo picture Matt Luongo · Feb 8, 2013

Why not use the csv module?

table = [[1,2,3],[4,5,6]]

import csv

# write it
with open('test_file.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    [writer.writerow(r) for r in table]

# read it
with open('test_file.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    table = [[int(e) for e in r] for r in reader]

This approach has the added benefit of making files that are readable by other programs, like Excel.

Heck, if you really need it space or tab-delimited, just add delimiter="\t" to your reader and writer construction.