[英]Building on “How to read and write a table / matrix to file with python?”
[英]How to read and write a table / matrix to file with python?
我正在嘗試創建一個程序,該程序接受數據並將其放在文本文件中僅數字的2 x 10表中。 然后程序需要在以后的迭代中檢索此信息。 但是我不知道該怎么做。 我一直在看一些笨拙的命令,常規文件命令以及嘗試創建表的方法。 但我似乎無法使這些工作正常進行。
這是我要制作的表格的示例:
0 1 1 1 0 9 6 5
5 2 7 2 1 1 1 0
然后,我將檢索這些值。 什么是這樣做的好方法?
為什么不使用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"
。
numpy
應該足夠了
table = np.loadtxt(filename)
這將具有形狀(2,10)。 如果要換位,只需在閉括號后添加.T
一行一行地處理:
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的評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.