How to read and write a table / matrix to file wit

2019-05-07 21:09发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

to handle the lines one-by-one:

with open('filename') as f:
   for ln in f:
       a = [int(x) for x in ln.split()]

or, to generate a two-dimensional array:

with open('filename') as f:
   a = [[int(x) for x in ln.split()] for ln in f]

Thanks Ord and Francesco Montesano for the comments