Python 如何将词典列表保存到文件中?
我有一份字典清单。有时,我希望更改并保存其中一个字典,以便在脚本重新启动时使用新消息。现在,我通过修改脚本并重新运行它来进行更改。我想把它从脚本中拉出来,并将字典列表放入某种配置文件中 我已经找到了如何将列表写入的答案,但这假设它是一个平面列表。我怎样才能用一系列字典来做呢 我的列表如下所示:Python 如何将词典列表保存到文件中?,python,list,file,dictionary,Python,List,File,Dictionary,我有一份字典清单。有时,我希望更改并保存其中一个字典,以便在脚本重新启动时使用新消息。现在,我通过修改脚本并重新运行它来进行更改。我想把它从脚本中拉出来,并将字典列表放入某种配置文件中 我已经找到了如何将列表写入的答案,但这假设它是一个平面列表。我怎样才能用一系列字典来做呢 我的列表如下所示: logic_steps = [ { 'pattern': "asdfghjkl", 'message': "This is not possible" },
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可以处理的对象(
列表
、元组
、字符串
、dicts
、数字
、无
、真
和假
),则可以将其转储为:
你将不得不遵循的方式将一个dict写入一个文件,这与你提到的帖子有所不同 首先,需要序列化对象,然后将其持久化。这些是“将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()
请注意,您可以像对待dict一样对待shelve对象。为了完整起见,我还添加了
json.dumps()
方法:
with open('outputfile_2', 'w') as file:
file.write(json.dumps(logic_steps, indent=4))
如果希望将每个字典放在一行中,请查看
json.dump()
和json.dumps()之间的差异:
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")
我得到错误类型错误:-0.69429028不是JSON SerializableDest_文件是什么?
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")