将字典写入文本文件? [英] Writing a dictionary to a text file?
问题描述
我有一本字典,正在尝试将其写入文件.
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)
然后我有错误
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))
错误:
file.write(str(exDict))
io.UnsupportedOperation: not writable
我不知道该怎么做,因为我仍然是 Python 的初学者.如果有人知道如何解决此问题,请提供答案.
I have no idea what to do as I am still a beginner at python. If anyone knows how to resolve the issue, please provide an answer.
注意:我使用的是 python 3,而不是 python 2
NOTE: I am using python 3, not python 2
推荐答案
首先,您以读取模式打开文件并尝试写入其中.咨询 - IO 模式 python
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 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
如果是序列化
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 包导入会有所不同
For python 3.x pickle package import would be different
import _pickle as pickle
这篇关于将字典写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!