【问题标题】:How to store tree structure in python permanently如何在python中永久存储树结构
【发布时间】:2020-10-09 12:17:43
【问题描述】:

我使用 python 创建了一个树形结构。假设树有根节点、左子节点和右子节点。我需要在需要时访问树。但是在打开文件并运行时会重新创建树。由于我在树中有大量节点,因此重新创建的方法非常耗时。请提供一个解决方案,以便我可以在需要时存储树、获取和更新(插入或删除节点)。

【问题讨论】:

  • 欢迎来到 StackOverflow。您的问题是广泛且缺乏信息和一个最小的工作示例。请访问stackoverflow.com/help 并在那里阅读以了解如何提问。除此之外,json 模块可能是你的朋友。我用它解决了类似的任务。

标签: python tree store permanent


【解决方案1】:

您可以使用pickle 模块,该模块可用于非常轻松地序列化和反序列化python 对象。

import pickle

tree = {'a': 'b'}
# serializing the data
with open('/path/to/some/file', 'wb') as f:
    pickle.dump(tree, f, pickle.HIGHEST_PROTOCOL)

# and deserializing it again
with open('/path/to/same/file', 'rb') as f:
    tree = pickle.load(f)

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多