Writing a dictionary to a text file? Writing a dictionary to a text file? python-3.x python-3.x

Writing a dictionary to a text file?


First of all you are opening file in read mode and trying to write into it.Consult - IO modes python

Secondly, you can only write a string to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it.

import json# as requested in commentexDict = {'exDict': exDict}with open('file.txt', 'w') as file:     file.write(json.dumps(exDict)) # use `json.loads` to do the reverse

In case of serialization

import cPickle as picklewith open('file.txt', 'w') as file:     file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse

For python 3.x pickle package import would be different

import _pickle as pickle


I do it like this in python 3:

with open('myfile.txt', 'w') as f:    print(mydictionary, file=f)


fout = "/your/outfile/here.txt"fo = open(fout, "w")for k, v in yourDictionary.items():    fo.write(str(k) + ' >>> '+ str(v) + '\n\n')fo.close()