pythonpython-3.xdictionaryfilefile-writing

Writing a dictionary to a text file?


I have a dictionary and am trying to write it to a file.

exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'r') as file:
    file.write(exDict)

I then have the error

file.write(exDict)
TypeError: must be str, not dict

So I fixed that error but another error came

exDict = {111:111, 222:222}
with open('file.txt', 'r') as file:
    file.write(str(exDict))

The error:

file.write(str(exDict))
io.UnsupportedOperation: not writable

How do I resolve this issue?


Solution

  • 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 or bytes 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 comment
    exDict = {'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 pickle
    
    with 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