在使用python編程過程中,我們往往需要藉助字典來提高編程效率。同時爲了調試方便,我們希望將某些變量保存爲中間文件。
例如,在協同過濾算法中,相似性的訓練結果可以保存爲中間文件,方便調試。python對字典的保存與讀取可以藉助於json方便
的實現。
-
#保存
-
dict_name = {1:{1:2,3:4},2:{3:4,4:5}}
-
f = open('temp.txt','w')
-
f.write(str(dict_name))
-
f.close()
-
#讀取
-
f = open('temp.txt','r')
-
a = f.read()
-
dict_name = eval(a)
-
f.close()