我有一本字典,正在尝试将其写入文件。
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 许可协议
首先,您以读取模式打开文件并尝试写入它。请教 -IO模式python
其次,您只能将字符串写入文件。如果你想写一个字典对象,你要么将它转换成字符串,要么将它序列化。
在序列化的情况下
对于 python 3.x pickle 包导入会有所不同