[python-3.x] 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

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

This question is related to python-3.x file dictionary file-writing

The answer is


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

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.


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

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

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/


import json

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

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 ]

I do it like this in python 3:

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

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

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to file-writing

Writing a dictionary to a text file? How do I specify new lines on Python, when writing on files? How to redirect 'print' output to a file using python?