将字典写入文本文件?

新手上路,请多包涵

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

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

然后我有错误

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

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

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

错误:

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

我该如何解决这个问题?

原文由 Nic 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 403
2 个回答

首先,您以读取模式打开文件并尝试写入它。请教 -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

在序列化的情况下

import cPickle as pickle

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

对于 python 3.x pickle 包导入会有所不同

import _pickle as pickle

原文由 hspandher 发布,翻译遵循 CC BY-SA 4.0 许可协议

我在 python 3 中这样做:

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

原文由 NKSHELL 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Stack Overflow 翻译
子站问答
访问
宣传栏