lxgeek
lxgeek

Reputation: 1814

Writing Python dictionary into a file

I want to write a dictionary into a file. The code is:

 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

As you see, I traverse the dictionary of store_dic and write in the file at the same time. Because I will call this code every 6 seconds, are there any ways to improve this?

Thank you.

Upvotes: 0

Views: 165

Answers (2)

Dileep
Dileep

Reputation: 2435

Saving a Python dict to a file using pickle:

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

The dict is loaded back from the file:

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

For more details, please follow this link:

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

Upvotes: 4

Kugel
Kugel

Reputation: 19864

Just use json module.

import json

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

with fs as open(store_file, "w"):
    json.dump(store_dic, fs)

Upvotes: 2

Related Questions