【发布时间】:2015-12-05 18:11:15
【问题描述】:
我有一个 JSON 文件(存储在 database.txt 中)我想在方法 addEvent() 中使用 python 字典进行修改:
def addEvent(eventName, start, end, place):
newdict={} #make a new dictionnary
newdict["NAME"]=eventName
newdict["START"]=start
newdict["END"]=end
newdict["place"]=place
try:
with open("database.txt",'r') as file:
content=file.read()
dict=json.loads(content) #make dictionnary with original JSON file
liste.append(newdict)
dico["event"]=liste #combine 2dictionnaries
with open("database.txt", 'w') as file:
file.write(str(dico)) #save my new JSON file
except:
...
我的问题: 我只能运行一次此方法,第二次收到错误消息:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
addEvent() 方法修改我的 database.txt 文件:它不再包含双引号而是重音,所以我不能第二次使用dict=json.loads(content)
我的问题我是否正确保存了我的 JSON 文件?如何在我的 database.txt 文件中保留 JSON 格式(保留双引号)?
【问题讨论】:
标签: python json python-3.x dictionary