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

被刻印的时光 ゝ 提交于 2019-12-12 09:45:02

问题


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



来源:https://stackoverflow.com/questions/14780702/how-to-read-and-write-a-table-matrix-to-file-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!