1.文件读写函数
文件读写 | 说明 |
np.save(string, ndarray) | 将ndarray保存到文件名为 [string].npy 的文件中(无压缩) |
np.savez(string, ndarray1, ndarray2, ...) | 将所有的ndarray压缩保存到文件名为[string].npy的文件中 |
np.savetxt(sring, ndarray, fmt, newline='\n') | 将ndarray写入文件,格式为fmt |
np.load(string) | 读取文件名string的文件内容并转化为ndarray对象(或字典对象) |
np.loadtxt(string, delimiter) | 读取文件名string的文件内容,以delimiter为分隔符转化为ndarray |
2.使用示例
np.save
# -*- coding: utf-8 -*-
import numpy as np
from tempfile import TemporaryFile
if __name__=='__main__':
outfile = TemporaryFile()
x = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
np.save(outfile, x)
outfile.seek(0) # Only needed here to simulate closing & reopening file
ret = np.load(outfile)
print(ret)
'''
[[1 2 3]
[4 5 6]
[7 8 9]]
'''
np.savez
# -*- coding: utf-8 -*-
import numpy as np
from tempfile import TemporaryFile
def np_savez():
outfile = TemporaryFile()
x = np.arange(10)
y = 2*x
#Using savez with *args, the arrays are saved with default names.
np.savez(outfile, x, y)
outfile.seek(0) # Only needed here to simulate closing & reopening file
npzfile = np.load(outfile)
ret = npzfile.files#['arr_0', 'arr_1']
print(npzfile['arr_0']) #[0 1 2 3 4 5 6 7 8 9]
print(npzfile['arr_1']) #[ 0 2 4 6 8 10 12 14 16 18]
if __name__=='__main__':
np_savez()
np.savetxt
def np_savetxt():
a=np.arange(5)
np.savetxt('001',a)
ret=np.loadtxt('001') #[ 0. 1. 2. 3. 4.]
np.savetxt('001', a*2)
ret = np.loadtxt('001')#[ 0. 2. 4. 6. 8.]
np.savetxt('001', (a,a*2))
ret = np.loadtxt('001')
#[[ 0. 1. 2. 3. 4.]
# [ 0. 2. 4. 6. 8.]]
print(ret)
if __name__=='__main__':
np_savetxt()
np.load
详见np.save
np.loadtxt
详见np.savetxt
(end)