簡體   English   中英

如何在txt文件中保存矩陣,然后在python中再次將其作為矩陣打開?

[英]How can I save a matrix in a txt file and then open it again as a matrix in python?

我試過這個:

  import numpy as np
  import os

  outdir= "directory"

  a = np.array([[1,2,3],[1,2,3]])

  os.chdir(outdir)

  np.savetxt("Image.bin", a)

  f = open("directory/Image.bin")
  m = np.fromfile(f, dtype=np.uint16)
  print len(m)
  ma = np.array(np.reshape(m, (2,3)))

  print ma

但它返回此錯誤消息:“新數組的總大小必須保持不變”

我試圖改變dtype,但它不起作用

你應該使用np.loadtxthttpnp.loadtxt

嘗試:

import numpy as np

a = np.array([[1,2,3],[1,2,3]])
np.savetxt("Image.bin", a)
m = np.loadtxt("Image.bin")

m現在包含在相同的陣列作為a

numpy內置了用於保存和加載數組作為二進制文件的函數。

numpy.save('data.npy', data)

將創建該文件(如果你沒有,它將附加npy),和

data = numpy.load('data.npy')

將從文件中加載它。 這比將它們保存為文本文件更快,更節省空間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM