我有一份字典的清单。有时,我希望更改并保存其中一个字典,以便在重新启动脚本时使用新消息。现在,我通过修改脚本并重新运行它来进行更改。我想从脚本中提取这个,并将字典列表放入某种类型的配置文件中。
我已经找到了如何将列表写入文件的答案,但这假设它是一个简单的列表。我怎样才能用字典列表来做呢?
我的列表如下:
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"
},
]
如果对象只包含json可以处理的对象(lists、tuples、strings、dicts、numbers、None、True和False,则可以将其作为json.dump转储:
import json
with open('outputfile', 'w') as fout:
json.dump(your_list_of_dict, fout)
我得到错误类型错误:-0.69429028不是JSON可序列化的
如果要将每个词典放在一行中:
import json
output_file = open(dest_file, 'w', encoding='utf-8')
for dic in dic_list:
json.dump(dic, output_file)
output_file.write("
")
为了完整起见,我还添加了json.dumps()方法:
with open('outputfile_2', 'w') as file:
file.write(json.dumps(logic_steps, indent=4))
。
这里看看json.dump()和json.dumps()之间的区别。
你将不得不遵循的方式写一个口述到一个文件是有点不同于你所提到的帖子。
首先,您需要序列化对象,而不是持久化它。这些是"将Python对象写入文件"的奇特名称。
默认情况下,python包含3个序列化模块,您可以使用这些模块来实现您的目标。它们是:泡菜、架子和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()
请注意,您可以像对待dict一样对待shelve对象。