numpy 文件读取 tofile,fromfile,load,save

tofile() 和fromfile()

tofile()输出的数据不保存数组形状和元素类型等信息

import numpy as np

a=np.arange(0,12)
print(a.dtype)
a=a.reshape(3,4)
print(a)

#tofile()将数组中的数据以二进制写进文件,保存文件的时候不保存数据的类型和形状等信息
a.tofile('hh.bin')

#fromfile()函数读取数据的时候需要指定数据的类型
# b=np.fromfile('hh.bin',dtype=np.float32)
b=np.fromfile('hh.bin',dtype=np.int32)
print(b)

int32
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[ 0  1  2  3  4  5  6  7  8  9 10 11] 

save() 和 load()

save()是numpy专用的保存二进制数据,会自动处理数据的类型的形状等信息。

如果想保存多个数据到文件中,可以使用savez()

import numpy as np

a=np.arange(0,12)
print(a.dtype)
a=a.reshape(3,4)
print(a)

b=np.arange(12,24)
print(b.dtype)
b=b.reshape(3,4)
print(b)

c=np.arange(24,36)
print(c.dtype)
c=c.reshape(3,4)
print(c)

# np.save('a.npy',a)
# c=np.load('a.npy')
# print(c)

#np.savez()保存多个数组,以字典的格式保存
# np.savez('hh.npz',a,b,c)
# hh=np.load('hh.npz')
# print(type(hh))
np.savez('hh.npz',a=a,b=b,c=c)
hh=np.load('hh.npz')
print('数据a',hh['a'])

int32
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
int32
[[12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]
int32
[[24 25 26 27]
 [28 29 30 31]
 [32 33 34 35]]
数据a [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]] 

savetxt()和loadtxt()

import numpy as np

a=np.arange(0,12)
print(a.dtype)
a=a.reshape(3,4)
print(a)

#保存为文本文件
np.savetxt('a.txt',a,fmt='%d',delimiter=',') #保存为整数,且以逗号分离
a=np.loadtxt('a.txt',delimiter=',')
print('数据a',a)

int32
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
数据a [[ 0.  1.  2.  3.]
 [ 4.  5.  6.  7.]
 [ 8.  9. 10. 11.]] 

你可能感兴趣的:(numpy)