0

我想将字典写入文件。代码是:

 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 秒调用一次这段代码,有什么办法可以改进吗?

谢谢你。

4

2 回答 2

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()

字典从文件中加载回来:

file = open('myfile.pkl', 'rb')
mydict = pickle.load(file)
file.close()

欲了解更多详情,请点击此链接:

http://www.saltycrane.com/blog/2008/01/saving-python-dict-to-file-using-pickle/

于 2012-11-06T05:05:38.140 回答
2

只需使用 json 模块。

import json

store_dic = { "key1": "value1", "key2": "value2" }

with fs as open(store_file, "w"):
    json.dump(store_dic, fs)
于 2012-11-06T05:01:27.190 回答