将字典写入文本文件?

Nic*_*Nic 59 dictionary file file-writing python-3.x

我有一本字典,我正在尝试将其写入文件.

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

然后我有错误

file.write(exDict)
TypeError: must be str, not dict
Run Code Online (Sandbox Code Playgroud)

所以我修复了这个错误,但又出现了另一个错

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

错误:

file.write(str(exDict))
io.UnsupportedOperation: not writable
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么办,因为我还是python的初学者.如果有人知道如何解决问题,请提供答案.

注意:我使用的是python 3,而不是python 2

hsp*_*her 100

首先,您在读取模式下打开文件并尝试写入文件.咨询 - IO模式python

其次,您只能将字符串写入文件.如果要编写字典对象,则需要将其转换为字符串或序列化.

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
Run Code Online (Sandbox Code Playgroud)

在序列化的情况下

import cPickle as pickle

with open('file.txt', 'w') as file:
     file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse
Run Code Online (Sandbox Code Playgroud)


NKS*_*ELL 26

我在python 3中这样做:

with open('myfile.txt', 'w') as f:
    print(mydictionary, file=f)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个,因为不需要导入。上面的答案 data.write(str(dictionary)) 不适用于正确的字典,因为它只会在您的文件中写入 <class 'dict'> (4认同)
  • with open('myfile.txt', 'r') as f: content = f.read(); dic = eval(内容); (3认同)

小智 18

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()
Run Code Online (Sandbox Code Playgroud)

  • 不鼓励仅代码的答案,因为他们没有解释他们如何解决问题.请更新您的答案,以解释这个问题如何改善这个问题已经存在的其他已接受和赞成的答案.请查看[我如何写出一个好的答案](https://stackoverflow.com/help/how-to-answer). (9认同)

小智 10

你的第一个代码块的问题是你打开文件为'r',即使你想用它写它 'w'

with open('/Users/your/path/foo','w') as data:
    data.write(str(dictionary))
Run Code Online (Sandbox Code Playgroud)


Dav*_*deL 6

对于列表理解爱好者,这将key : value在新行中写入所有对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 ]
Run Code Online (Sandbox Code Playgroud)


Mar*_*ews 5

如果您想要字典,则可以按名称从文件导入,并且还添加了排序合理的条目,并且包含要保留的字符串,您可以尝试以下操作:

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("}")
Run Code Online (Sandbox Code Playgroud)

然后导入:

from file import dictionary_name
Run Code Online (Sandbox Code Playgroud)