如何将NumPy数组保存为较大文本文件的一部分?我可以使用savetxt
将数组写入临时文件,然后将它们读回字符串,但这似乎是冗余和低效的编码(某些数组会很大)。例如:
from numpy import *
a=reshape(arange(12),(3,4))
b=reshape(arange(30),(6,5))
with open ('d.txt','w') as fh:
fh.write('Some text\n')
savetxt('tmp.txt', a, delimiter=',')
with open ("tmp.txt", "r") as th:
str=th.read()
fh.write(str)
fh.write('Some other text\n')
savetxt('tmp.txt', b, delimiter=',')
with open ("tmp.txt", "r") as th:
str=th.read()
fh.write(str)
答案 0 :(得分:2)
fname :文件名或 文件句柄
因此,您可以在append mode中打开文件并写信给它:
with open ('d.txt','a') as fh:
fh.write('Some text\n')
savetxt(fh, a, delimiter=',')
fh.write('Some other text\n')
savetxt(fh, b, delimiter=',')