归纳一下python中不同数据保存格式的存储和读取,旨在方法整理和速度比较。
从数据角度分两种,一是ndarray格式的纯数值数据的读写,二是对象(数据结构)如dict的文件存取。
数值数据的读写
.bin格式,np.tofile() 和 np.fromfile()
import numpy as np
a = np.random.randint(0, 100, size=(10000, 5000))
print(a.dtype, a.shape) # int32 (10000, 5000) 下同
a.tofile('data/a.bin')
b = np.fromfile('data/a.bin', dtype=np.int32) # 需要设置正确dtype
print(b.shape) # (50000000,) 读入数据是一维的,需要reshape
.npy格式,np.save() 和 np.load()
numpy专用的二进制格式保存数据,能自动处理变量type和size
np.save('data/a.npy', a)
b = np.load('data/a.npy')
print(b.shape) # (10000, 5000)
.txt格式 (或.csv/.xlsx),np.savetxt() 和 np.loadtxt()
csv或xlsx可以借助python其他库工具实现。csv只能存数字,xlsx可以存数字字符。
np.savetxt('data/a.txt', a, fmt='%d', delimiter=