Python的numpy模块提供了一个名为numpy.save()的函数,用于将数组保存为.npy格式的二进制文件。
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
file:str,file或pathlib.path
此参数定义将在其中保存数据的文件或文件名。如果此参数是文件的对象,则文件名将保持不变。如果 file 参数是路径或字符串,则.npy扩展名将添加到文件名。
allow_pickle:bool(可选)
此参数用于允许将对象保存到泡菜中。安全性和可能性是不允许泡菜的原因。
fix_imports:bool(可选)
如果fix_imports设置为True,则pickle会将新的Python3名称映射到在Python2中使用的旧模块名称。这使得泡菜数据流可以用Python2读取。
import numpy as np from tempfile import TemporaryFile out_file = TemporaryFile() x=np.arange(15) np.save(out_file, x) _=out_file.seek(0) # Only needed here to simulate closing & reopening file np.load(outfile)
输出:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
在上面的代码中:
在输出中,显示了一个数组,其中包含 out_file.npy 中存在的元素。
import numpy as np from tempfile import TemporaryFile outfile = TemporaryFile() x=np.arange(15) np.save(outfile, x, allow_pickle=False) _=outfile.seek(0) # Only needed here to simulate closing & reopening file np.load(outfile)
输出:
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)