繁体   English   中英

将numpy数组保存为更大的文本文件的一部分

[英]Saving numpy arrays as part of a larger text file

如何将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)

savetxt的第一个参数

fname :文件名或文件句柄

因此,您可以在追加模式下打开文件并写入文件:

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=',')

暂无
暂无

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

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