Python 3 numpy.load() until End of File

孤人 提交于 2021-02-11 12:27:10

问题


Suppose I'm generating a random number of arrays that I need to serialize

def generator():
    num = 0
    while num < random.randint(0, 10):
        yield np.array(range(2))
        num += 1


with open('out.npy', 'wb') as f:
    for item in generator():
        np.save(f, item)

Now how do I know exactly how many times I have to np.load() to get all the arrays back? np.load() will eventually throw an exception so I came up with

with open('out.npy', 'rb') as f:
    try:
        while 1:
            item = np.load(f)
            print(item)
    except:
        print("EoF")

but I wonder if there is a way to detect End of File or just a better way to do this.


回答1:


Did you try the following?

data = np.load('out.npy')

reference: https://numpy.org/doc/stable/reference/generated/numpy.load.html



来源:https://stackoverflow.com/questions/62596678/python-3-numpy-load-until-end-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!