我想将字典写入文件。代码是:
fs = open( store_file , "w" )
for k in store_dic:
temp_line = k + " " + store_dic[k] + "\n"
fs.write( temp_line )
logger.info( "store_record " + store_file + " " + temp_line[:-1] )
fs.close
如您所见,我遍历store_dic字典并同时写入文件。 还有其他方法来改善这个吗?因为我会每6秒调用一次此代码。
谢谢。
答案 0 :(得分:4)
使用pickle
将Python dict保存到文件中import pickle
# write python dict to a file
mydict = {'a': 1, 'b': 2, 'c': 3}
output = open('myfile.pkl', 'wb')
pickle.dump(mydict, output)
output.close()
有关详细信息,请点击此链接
http://www.saltycrane.com/blog/2008/01/saving-python-dict-to-file-using-pickle/
答案 1 :(得分:2)
只需使用json模块。
import json
store_dic = { "key1": "value1", "key2": "value2" }
with fs as open(store_file, "w"):
json.dump(store_dic, fs)