【问题标题】:How can I save a list of dictionaries to a file?如何将字典列表保存到文件中?
【发布时间】:2014-11-04 20:18:35
【问题描述】:

我有一个字典列表。有时,我想更改并保存其中一个字典,以便在重新启动脚本时使用新消息。现在,我通过修改脚本并重新运行它来进行更改。我想将其从脚本中提取出来,并将字典列表放入某种配置文件中。

我找到了有关如何将列表写入file 的答案,但这假设它是一个平面列表。如何使用字典列表来做到这一点?

我的列表如下所示:

logic_steps = [
    {
        'pattern': "asdfghjkl",
        'message': "This is not possible"
    },
    {
        'pattern': "anotherpatterntomatch",
        'message': "The parameter provided application is invalid"
    },
    {
        'pattern': "athirdpatterntomatch",
        'message': "Expected value for debugging"
    },
]

【问题讨论】:

    标签: python list file dictionary


    【解决方案1】:

    如果您希望每部字典都在一行中:

     import json
     output_file = open(dest_file, 'w', encoding='utf-8')
     for dic in dic_list:
        json.dump(dic, output_file) 
        output_file.write("\n")
    

    【讨论】:

    • 什么是dest_file?
    • @ElizaR dest_file 是目标文件的位置。这可能类似于 linux 上的 /home/user/file
    【解决方案2】:

    为了完整起见,我还添加了json.dumps() 方法:

    with open('outputfile_2', 'w') as file:
        file.write(json.dumps(logic_steps, indent=4))
    

    看看herejson.dump()json.dumps()之间的区别

    【讨论】:

      【解决方案3】:

      将字典写入文件必须遵循的方式与您提到的帖子有点不同。

      首先,您需要序列化对象,然后将其持久化。这些是“将 python 对象写入文件”的花哨名称。

      Python 默认包含 3 个序列化模块,您可以使用它们来实现您的目标。它们是:pickle、shelve 和 json。每一个都有自己的特点,你必须使用的那个是更适合你的项目的。您应该检查每个模块文档以了解更多信息。

      如果你的数据只会被python代码访问,你可以使用shelve,这里是一个例子:

      import shelve
      
      my_dict = {"foo":"bar"}
      
      # file to be used
      shelf = shelve.open("filename.shlf")
      
      # serializing
      shelf["my_dict"] = my_dict
      
      shelf.close() # you must close the shelve file!!!
      

      要检索数据,您可以这样做:

      import shelve
      
      shelf = shelve.open("filename.shlf") # the same filename that you used before, please
      my_dict = shelf["my_dict"]
      shelf.close()
      

      看到你可以像对待字典一样对待搁置对象。

      【讨论】:

        【解决方案4】:

        如果对象只包含JSON可以处理的对象(liststuplesstringsdictsnumbersNoneTrueFalse),你可以转储为json.dump:

        import json
        with open('outputfile', 'w') as fout:
            json.dump(your_list_of_dict, fout)
        

        【讨论】:

        • 我收到错误 TypeError: -0.69429028 is not JSON serializable
        • 当我从文件中导入数据时,我需要在 json.dump 之前添加 fout.write("data = ")
        猜你喜欢
        • 2021-07-04
        • 1970-01-01
        • 2021-03-23
        • 2013-10-12
        • 2021-09-28
        • 2018-04-10
        • 2017-07-14
        • 2018-12-20
        相关资源
        最近更新 更多