1. 數組以二進制格式保存
np.save和np.load是讀寫磁盤數組數據的兩個主要函數。默認情況下,數組以未壓縮的原始二進制格式保存在擴展名為npy的文件中,以數組a為例
np.save("filename.npy",a)
b = np.load("filename.npy")
利用這種方法,保存文件的后綴名字一定會被置為.npy
2. 存取文本文件
使用 np.savetxt 和 np.loadtxt 只能讀寫 1 維和 2 維的數組
np.savetxt:將數組寫入以某種分隔符隔開的文本文件中
np.loadtxt:指定某種分隔符,將文本文件讀入到數組中
np.savetxt("filename.txt",a)
b = np.loadtxt("filename.txt", delimiter=',')
3. 保存為二進制文件
使用數組的 tofile 函數可以方便地將數組中數據以二進制的格式寫進文件
a.tofile("filename.bin")
b = np.fromfile("filename.bin",dtype = **)
該方法與np.save有幾點區別:
- tofile函數只能將數組保存為二進制文件,文件后綴名沒有固定要求。這種保存方法對數據讀取有要求,np.fromfile 需要手動指定讀出來的數據的的dtype,如果指定的格式與保存時的不一致,則讀出來的就是錯誤的數據。
- tofile函數不能保存當前數據的行列信息,不管數組的排列順序是C語言格式的還是Fortran語言格式,統一使用C語言格式輸出。因此使用 np.fromfile 讀出來的數據是一維數組,需要利用reshape指定行列信息。
例如下面的例子所示:
>>> a = np.arange(0,12)
>>> a.shape = 3,4
>>> a array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> a.tofile("a.bin")
>>> b = np.fromfile("a.bin", dtype=np.float) # 按照float類型讀入數據
>>> b # 讀入的數據是錯誤的 array([ 2.12199579e-314, 6.36598737e-314, 1.06099790e-313,
1.48539705e-313, 1.90979621e-313, 2.33419537e-313]) >>> a.dtype # 查看a的dtype dtype('int32')
>>> b = np.fromfile("a.bin", dtype=np.int32) # 按照int32類型讀入數據
>>> b # 數據是一維的 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> b.shape = 3, 4 # 按照a的shape修改b的shape
>>> b array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
參考資料 : http://blog.csdn.net/pipisorry/article/details/39088003