【发布时间】:2018-05-14 01:44:44
【问题描述】:
我有一本 Python 字典。我想修改该字典,然后将字典保存到外部文件,这样当我再次加载 python 程序时,它会从外部文件中获取字典数据。
class Data:
"""
Data handling class to save
and receive json data, parent
of User for data purposes.
"""
def saveData(data, file):
with open(file, 'r+') as dataFile:
dataFile.write(json.dumps(data))
def getData(file):
with open(file, 'r+') as dataFile:
return json.loads(dataFile.readline())
def deleteContent(file):
file.seek(0)
file.truncate()
但是当我写入文件然后尝试读取它时,它将它作为字符串读取,我不能使用读取的数据来设置字典。如何从外部 JSON 文件中获取字典中的数据作为字典数据,而不是字符串数据?
data = Data.getData("chatbotData.json")
dataDict = data
dataDict["age"] = 2
这是我想要对数据执行的操作,但出现此错误:
TypeError: 'str' 对象不支持项目分配
【问题讨论】:
-
首先尝试使用
json.dump(dataFile, data)(或切换参数顺序,我不记得了和return json.load(dataFile)。还有为什么不直接使用r和w文件模式?
标签: python json python-3.x dictionary