问题描述
我有一个扩展名为 .npz 的文件。我怎样才能确定它的形状。 我用这段代码在 colab 上加载了它
import numpy as np
file=np.load(path/to/.npz)
我无法确定它的形状
解决方法
生成示例 .npz
文件
import numpy as np
import zipfile
x = np.arange(10)
y = np.sin(x)
np.savez("out.npz",x,y)
def npz_headers(npz):
"""
Takes a path to an .npz file,which is a Zip archive of .npy files.
Generates a sequence of (name,shape,np.dtype).
"""
with zipfile.ZipFile(npz) as archive:
for name in archive.namelist():
if not name.endswith('.npy'):
continue
npy = archive.open(name)
version = np.lib.format.read_magic(npy)
shape,fortran,dtype = np.lib.format._read_array_header(npy,version)
yield name[:-4],dtype
print(list(npz_headers("out.npz")))
调用上面的函数,它返回下面的输出
[('arr_0',(10,),dtype('int64')),('arr_1',dtype('float64'))]