简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM