如何使用python读取和写入表/矩阵到文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14780702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read and write a table / matrix to file with python?
提问by YamSMit
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.
我正在尝试创建一个程序,该程序接收数据并将其放入文本文件中仅包含数字的 2 x 10 表格中。然后程序需要在以后的迭代中检索这些信息。但我不知道该怎么做。我一直在研究 numpty 命令、常规文件命令以及尝试制作表格的方法。但我似乎无法让这些工作。
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?
然后我会检索这些值。有什么好的方法可以做到这一点?
回答by gefei
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
感谢 Ord 和 Francesco Montesano 的评论
回答by Francesco Montesano
numpyshould be enough
numpy应该够了
table = np.loadtxt(filename)
this will have shape (2,10). If you want it transposed, just add a .Tjust after the closed bracket
这将具有形状 (2,10)。如果你想要它转置,只需.T在闭合括号后添加一个
回答by Matt Luongo
Why not use the csvmodule?
为什么不使用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]
This approach has the added benefit of making files that are readable by other programs, like Excel.
这种方法的另一个好处是使文件可以被其他程序(如 Excel)读取。
Heck, if you really need it space or tab-delimited, just add delimiter="\t"to your reader and writer construction.
哎呀,如果您真的需要空格或制表符分隔,只需添加delimiter="\t"到您的读写器结构中即可。

