簡體   English   中英

如何將字典列表保存到文件中?

[英]How can I save a list of dictionaries to a 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"
    },
]

如果該對象只包含JSON可以處理的對象( liststuplesstringsdictsnumbersNoneTrueFalse ),則可以將其轉儲為json.dump

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

為了完整性,我還添加了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")

將dict寫入文件必須遵循的方式與您提到的帖子有所不同。

首先,您需要序列化對象而不是持久化對象。 這些是“將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一樣處理擱置對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM