如何使用python读取和写入表/矩阵到文件?

时间:2013-02-08 20:20:36

标签: python matrix file-io tabular

我正在尝试创建一个程序来获取数据并将其放入文本文件中的2×10数字表中。然后程序需要在以后的迭代中检索此信息。但我不知道该怎么做。我一直在研究numpty命令,常规文件命令以及尝试创建表的方法。但我似乎无法让这一切发挥作用。

以下是我要尝试制作的表的示例:

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

然后我会检索这些值。有什么好办法呢?

3 个答案:

答案 0 :(得分:7)

为什么不使用csv模块?

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]

这种方法的另一个好处是可以制作其他程序可读的文件,例如Excel。

哎呀,如果你确实需要空格或制表符分隔,只需将delimiter="\t"添加到你的读写器构造中。

答案 1 :(得分:3)

numpy应该足够了

table = np.loadtxt(filename)

这将具有形状(2,10)。如果您想要转置,只需在闭括号

之后添加.T即可

答案 2 :(得分:1)

逐个处理这些行:

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

或者,生成二维数组:

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

感谢Ord和Francesco Montesano的评论