从文本文件从anytree创建一个巨大的树(Python)

2024-04-28 13:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一些巨大的树,我希望能够将它们存储在文本文件中,并在其他地方重建它们,而不必每次都重新创建树。在

我用AnyTree做我的树。不支持numpy数组,因此不支持numpy数组转换。我将它们导出为嵌套字典。在

这就是我如何将树写入文本文件的方法。在

#Exports the tree to the given filename as a dictionary
def TreetoDict(filename, root):
    exporter = DictExporter()
    dictoutput = exporter.export(root)
    string = str(dictoutput)
    with open(filename,"w") as f:
        f.write(string)
        f.close()
    print("Finished writing")
    return dictoutput

因为这棵树太大了,我想在未经我同意的情况下,把字典变成一个字符串,用“”的形式放了很多换行符。在

这就是文本文件的样子。在

^{pr2}$

如何将字典格式化为一个字符串,放入一个文本文件中,然后读取该文本文件来重建树?在


Tags: the方法字符串numpystring字典as地方