【问题标题】:How to load/view structure of pickled object in Ipython console ? (Windows 7, Spyder, Ipython console)如何在 Ipython 控制台中加载/查看腌制对象的结构? (Windows 7、Spyder、Ipython 控制台)
【发布时间】:2017-07-26 03:58:19
【问题描述】:

我正在学习其他程序员编写的程序。所以我想查看腌制项目的结构。 由于我需要知道腌制数据的结构,我正在尝试使用 Spyder 在 Ipython 中加载腌制......例如:

import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
#selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

我想知道这里腌制的 .pkl 文件的结构。

【问题讨论】:

    标签: python-3.x ipython pickle spyder


    【解决方案1】:

    不清楚您所说的structure 是什么意思。如果我运行你的代码,我可以这样做:

    In [6]: with open('data.pkl','rb') as f:
       ...:     x = pickle.load(f)
       ...:     y = pickle.load(f)
       ...:     
       ...:     
    In [7]: x
    Out[7]: {'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
    In [8]: y
    Out[8]: [1, 2, 3]
    

    我可以通过相同数量的读取恢复您的连续写入。如果我尝试获得更多信息,我会收到 EOFError: Ran out of input

    你想知道什么?文件上有多少对象?每个对象的结构? Python 对象与文件中字节的转换?

    【讨论】:

    • 感谢您的回答。实际上,我想在控制台中检索腌制数据。我想知道是否可以在不加载的情况下知道腌制对象包含什么类型的数据例如:type(x) is dict type(y): list
    • 因为当我们知道只有 2 个项目被腌制时,我们可以给 2 次加载 pickle x = pickle.load(f) y = pickle.load(f) 但当我们不知道有多少物品都在那里...那么如何处理这些问题。
    【解决方案2】:

    当我们不知道腌制了多少物品时该怎么办...

    找到答案:

    unpickled_store = []
    file_id = open('data.pkl','rb')
    while True:
            try:
                unpickled_item = pickle.load(file_id)
                unpickled_store.append(unpickled_item)
            except EOFError:
                break
    

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 1970-01-01
      • 2017-03-09
      • 2018-01-05
      • 2021-11-09
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多