代码之家  ›  专栏  ›  技术社区  ›  Håkon Hægland

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

  •  0
  • Håkon Hægland  · 技术社区  · 10 年前

    如何将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)
    
    1 回复  |  直到 10 年前
        1
  •  2
  •   RomanHotsiy    10 年前

    的第一个参数 savetxt

    文件名 :文件名或 文件句柄

    因此,您可以在 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=',')