如何在 pickle 文件 python 中加载一些变量?与使用 scipy 或 hdf5storage 加载 matlab 文件一样

how to load some of the variables in a pickle file python? As in loading matlab files using scipy or hdf5storage

假设我保存了一个包含多个变量的 pickle 文件:

import pickle

with open("file.pickle", "wb") as f:
    pickle.dump((a,b,c,d,e,f), f)

文件可以加载:

with open("file.pickle", "rb") as f:
    a,b,c,d,e,f= pickle.load(f) 

有没有办法只读取前四个变量,而不是将这四个变量保存在一个单独的文件中?

with open("file.pickle", "rb") as f:
    a,b,c,d=  ?? #load the first four variables only

您没有将 6 个变量保存到 pickle 文件中。这不是泡菜或变量的工作方式。

您构建了一个 6 元素元组并将该元组的 pickle 格式序列化写入文件。 pickle 格式不支持仅反序列化序列化对象的一部分;你必须加载整个元组。

pickle 格式是构建对象的一系列指令,就像按照一半的食谱烤蛋糕不会烤半个蛋糕一样,你不能加载半个 pickle 并获得一半的元组序列化。