Search code examples
python-2.7dictionaryfwrite

How to write a dictionary in a file Python?


Hi would like to store a dictionary in a file but my code doesn't work.

Here the code:

d=open('dict.txt', 'w')
for key, v in dict_ens.iteritems(): # dict_ens is another dict i have
    dict_ens[key]=dict_ens[key][2:]
    if key in enstts: #
       d.write(key, v)
    else : 
       d.write('no key')

d.close()   

what could be wrong with that???


Solution

  • There are several possible ways your code could fail, but without a reproducible example or the error message I can't give you a specific reason.

    I would suggest an alternative approach. A simple way to save a dictionary is using the "pickle" library.

    To save the dictionary as a pickle file, try this:

    import pickle
    with open('path_and_filename.pickle', 'wb') as handle:
        pickle.dump(name_of_dict, handle)
    

    You can open a saved dictionary like this:

    with open('path_and_filename.pickle', 'r') as handle:
        variable_name = pickle.load(handle)