简体   繁体   English

如何在泡菜文件 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

Let's say I have saved a pickle file with multiple variables:假设我保存了一个包含多个变量的泡菜文件:

import pickle

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

The file can be loaded with:该文件可以加载:

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

Is there a way to read just the first four variables other than saving the four variables in a separate file?除了将四个变量保存在单独的文件中之外,有没有办法只读取前四个变量?

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

You didn't save 6 variables to a pickle file.您没有将 6 个变量保存到泡菜文件中。 That's not how pickles or variables work.这不是泡菜或变量的工作方式。

You constructed a 6-element tuple and wrote a pickle-format serialization of that tuple to a file.您构建了一个 6 元素元组并将该元组的 pickle 格式序列化写入文件。 The pickle format does not support deserializing only parts of a serialized object; pickle 格式不支持仅反序列化序列化 object 的一部分; you have to load the whole tuple.你必须加载整个元组。

The pickle format is a sequence of instructions for building objects, and just like following half the recipe to bake a cake won't bake half a cake, you can't load half a pickle and get half the tuple you serialized. pickle 格式是用于构建对象的一系列指令,就像按照半个食谱烤蛋糕不会烤半个蛋糕一样,你不能加载半个泡菜并获得你序列化的一半元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM