我有一本字典,正在尝试将其写入文件。
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
如何解决这个问题?
请您参考如下方法:
首先,您以读取模式打开文件并尝试写入其中。 咨询-IO modes 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