Writing a dictionary to a text file?

Python 3.xFileDictionaryFile Writing

Python 3.x Problem Overview


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

I have no idea what to do as I am still a beginner at python. If anyone knows how to resolve the issue, please provide an answer.

NOTE: I am using python 3, not python 2

Python 3.x Solutions


Solution 1 - Python 3.x

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

Solution 2 - Python 3.x

I do it like this in python 3:

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

Solution 3 - Python 3.x

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

Solution 4 - Python 3.x

The probelm with your first code block was that you were opening the file as 'r' even though you wanted to write to it using 'w'

with open('/Users/your/path/foo','w') as data:
    data.write(str(dictionary))

Solution 5 - Python 3.x

If you want a dictionary you can import from a file by name, and also that adds entries that are nicely sorted, and contains strings you want to preserve, you can try this:

data = {'A': 'a', 'B': 'b', }

with open('file.py','w') as file:
    file.write("dictionary_name = { \n")
    for k in sorted (data.keys()):
        file.write("'%s':'%s', \n" % (k, data[k]))
    file.write("}")

Then to import:

from file import dictionary_name

Solution 6 - Python 3.x

For list comprehension lovers, this will write all the key : value pairs in new lines in dog.txt

my_dict = {'foo': [1,2], 'bar':[3,4]}

# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]

# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
    [ my_file.write(f'{st}\n') for st in list_of_strings ]

Solution 7 - Python 3.x

I know this is an old question but I also thought to share a solution that doesn't involve json. I don't personally quite like json because it doesn't allow to easily append data. If your starting point is a dictionary, you could first convert it to a dataframe and then append it to your txt file:

import pandas as pd
one_line_dict = exDict = {1:1, 2:2, 3:3}
df = pd.DataFrame.from_dict([one_line_dict])
df.to_csv('file.txt', header=False, index=True, mode='a')

I hope this could help.

Solution 8 - Python 3.x

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

Solution 9 - Python 3.x

You can do as follow :

import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))

https://developer.rhino3d.com/guides/rhinopython/python-xml-json/

Solution 10 - Python 3.x

import json

with open('tokenler.json', 'w') as file:
     file.write(json.dumps(mydict, ensure_ascii=False))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicView Question on Stackoverflow
Solution 1 - Python 3.xhspandherView Answer on Stackoverflow
Solution 2 - Python 3.xNKSHELLView Answer on Stackoverflow
Solution 3 - Python 3.xSange NegruView Answer on Stackoverflow
Solution 4 - Python 3.xclyde_the_frogView Answer on Stackoverflow
Solution 5 - Python 3.xMarMatView Answer on Stackoverflow
Solution 6 - Python 3.xDavideLView Answer on Stackoverflow
Solution 7 - Python 3.xAngeloView Answer on Stackoverflow
Solution 8 - Python 3.xianzoView Answer on Stackoverflow
Solution 9 - Python 3.xShivam VermaView Answer on Stackoverflow
Solution 10 - Python 3.xMehmet Ali BayramView Answer on Stackoverflow