首页 > 解决方案 > 读取 .npy 文件时检索错误

问题描述

我正在尝试读取一个大的 .npy 文件,但我无法读取该文件。下面是我用于读取文件的 python 代码。

import numpy as np

pre_train = np.load('weights.npy',allow_pickle=True, encoding="latin1")
data_pic = pre_train.item()
#print(type(data_dic))
for item in data_pic:
    print(item)

错误:data_pic = pre_train.item()

Can only convert an array of size 1 to a Python scalar

标签: pythonpython-3.xnumpy

解决方案


加载文件时您的代码不会崩溃。使用numpy.ndarray.item时崩溃。在您的情况下,您不需要使用item().

使用一个好的旧 for 循环就可以了!

data = np.load('...')
for i in data:
    for j in i:
        print(j)

# 2, 2, 6, 1, ...

推荐阅读