Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 607
YamSMit Avatar asked Dec 16 '22 14:12

YamSMit


2 Answers

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.

like image 99
Matt Luongo Avatar answered Jan 10 '23 19:01

Matt Luongo


numpy should be enough

table = np.loadtxt(filename)

this will have shape (2,10). If you want it transposed, just add a .T just after the closed bracket

like image 35
Francesco Montesano Avatar answered Jan 10 '23 20:01

Francesco Montesano