3 回答

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個贊
使用jsonorpickle比保存明文并對其進(jìn)行ast.literal_evaling更好。我會推薦json:
對于json,首先運(yùn)行一次:
import json
with open('baseDict.json', 'w') as f:
json.dump({'a':10, 'b':20, 'c':30, 'd':40}, f)
然后:
import json
with open('baseDict.json','r') as f:
baseDict = json.load(f)
# your code
with open('baseDict.json', 'w') as f:
json.dump(baseDict, f)
請參閱此處了解為什么json比ast.literal_eval.

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個贊
據(jù)我所知,保持這種更改的唯一方法是使用本地存儲。它可以與 Jsons、文本文件、數(shù)據(jù)庫一起使用,甚至您可以創(chuàng)建自己的編碼類型的文件。不過,大多數(shù)應(yīng)用程序都需要安裝,也許將您的數(shù)據(jù)加密并將其存儲在應(yīng)用程序在安裝過程中創(chuàng)建的目錄中的秘密文件中,這可能是您的選擇。

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個贊
你可以把它保存到txt,然后再加載回來。
所以自己運(yùn)行一個代碼,如下所示:
with open('test.txt','w') as f:
f.write("{'a':10, 'b':20, 'c':30, 'd':40}")
然后,使用以下代碼運(yùn)行另一個模塊:
import ast
with open('test.txt','r') as f:
baseDict=ast.literal_eval(f.read().rstrip())
def updateDict(key, value):
temp = {key : value}
baseDict.update(temp)
return baseDict
key = str(input('Enter key\n'))
value = input('Enter value\n')
baseDict = updateDict(key, value)
with open('test.txt','w') as f:
f.write(str(baseDict))
添加回答
舉報