147

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?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Nic
  • 1,549
  • 2
  • 13
  • 13

11 Answers11

220

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
hspandher
  • 15,934
  • 2
  • 32
  • 45
92

I do it like this in python 3:

with open('myfile.txt', 'w') as f:
    print(mydictionary, file=f)
NKSHELL
  • 1,069
  • 8
  • 8
  • If your dict is not just regular string/numbers data put contains sets/list etc. as values and you want to print the dict to a text file, this is the way to go. – Bikash Gyawali Jun 20 '23 at 10:36
31
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()
MaNKuR
  • 2,578
  • 1
  • 19
  • 31
Sange Negru
  • 327
  • 3
  • 2
  • 16
    Code-only answers are discouraged because they do not explain how they resolve the issue. Please update your answer to explain how this improves on the other accepted and upvoted answers this question already has. Please review [How do I write a good answer](https://stackoverflow.com/help/how-to-answer). – FluffyKitten Sep 10 '17 at 07:59
  • 1
    Also, you should use the `with` statement when reading from and writing to files: https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for – Falko Jan 15 '18 at 17:58
19

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))
Erty Seidohl
  • 4,487
  • 3
  • 33
  • 45
clyde_the_frog
  • 199
  • 1
  • 2
11

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
MarMat
  • 790
  • 8
  • 12
6

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 ]
DavideL
  • 294
  • 1
  • 3
  • 15
2

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.

Angelo
  • 1,594
  • 5
  • 17
  • 50
1
exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'w+') as file:
    file.write(str(exDict))
ianzo
  • 11
  • 1
0

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/

LaSul
  • 2,231
  • 1
  • 20
  • 36
0

In my case, I have to write the dictionary in a file but in YAML format. I found this question here helpful but the answers were only in JSON or String. Hence I'm adding my exploration here - so that it may help others for YAML format.

import yaml

my_dictionary = {
    "numbers": ["one", "two", "three"],
    "colours": ["blue", "pink"],
    "name": "Santosh"
}

with open("test.yaml", "w") as file:
    file.write(yaml.dump(my_dictionary))

Output in test.yaml file is,

colours:
- blue
- pink
name: Santosh
numbers:
- one
- two
- three

Hope this helps!

Santosh Kumar Arjunan
  • 3,600
  • 3
  • 23
  • 24
-2
import json

with open('tokenler.json', 'w') as file:
     file.write(json.dumps(mydict, ensure_ascii=False))
Mehmet Ali Bayram
  • 7,222
  • 2
  • 22
  • 27