简体   繁体   English

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

[英]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. 我正在尝试创建一个程序,该程序接受数据并将其放在文本文件中仅数字的2 x 10表中。 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? 为什么不使用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"

numpy should be enough numpy应该足够了

table = np.loadtxt(filename)

this will have shape (2,10). 这将具有形状(2,10)。 If you want it transposed, just add a .T just after the closed bracket 如果要换位,只需在闭括号后添加.T

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的评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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