python使用numpy读取、保存txt数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AManFromEarth/article/details/80259649

1.首先生成array数组

import numpy as np
a = np.random.rand(5,5)
print(a)

结果:

array([[0.17374613, 0.87715267, 0.93111376, 0.53415215, 0.59667207],
       [0.6865835 , 0.15873242, 0.2842251 , 0.73840834, 0.37163279],
       [0.06556834, 0.68446787, 0.91136611, 0.82796704, 0.81343561],
       [0.99336674, 0.22961447, 0.78337783, 0.12448455, 0.04388831],
       [0.50053951, 0.046609  , 0.98179001, 0.446681  , 0.68448799]])

2.保存至txt
使用numpy.savetxt函数,文档在这里:
https://docs.scipy.org/doc/numpy-1.14.2/reference/generated/numpy.savetxt.html#numpy.savetxt

np.savetxt('a.txt',a,fmt='%0.8f')
#第一个参数是要保存的文件名
#第二参数是要保存的array
#第三个参数是保存的数据格式,详见文档

结果:
这里写图片描述

3.从txt文件中读取数据

b=np.loadtxt('a.txt',dtype=np.float32)
print(b)

结果:

array([[0.17374612, 0.8771527 , 0.9311138 , 0.53415215, 0.59667206],
       [0.6865835 , 0.15873241, 0.2842251 , 0.7384083 , 0.37163278],
       [0.06556834, 0.68446785, 0.9113661 , 0.82796705, 0.8134356 ],
       [0.9933667 , 0.22961447, 0.7833778 , 0.12448455, 0.04388831],
       [0.5005395 , 0.046609  , 0.98179   , 0.446681  , 0.684488  ]],
      dtype=float32)

猜你喜欢

转载自blog.csdn.net/AManFromEarth/article/details/80259649