【Python】【numpy-汇总6】所有文件读写函数的示例代码

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值