【发布时间】:2021-04-16 20:18:43
【问题描述】:
您好,我正在尝试创建 JSON 文件,但无法格式化文件。 下面我将提供代码和输出。
代码:
def writeToFile(self):
self.json_conceivement = os.path.join("./",'NoobPremeNewEggLogIn.json')
self.accounts = {}
if os.path.exists(self.json_conceivement):
try:
with open(self.json_conceivement) as f:
self.accounts = dict(json.loads(f.read()))
except:
pass
self.accounts = {}
else:
try:
with open(self.json_conceivement) as f:
self.accounts = {}
except:
pass
self.accounts['Profiles'] = []
self.autoSave()
def autoSave(self):
with open(self.json_conceivement, "a", encoding='utf-8') as outfile:
json.dump(dict(self.accounts.items()), outfile,ensure_ascii=False, indent=4)
输出:(如果我运行一次,预计)
{
"Profiles": []
}
输出:(如果我运行两次,不正确)
{
"Profiles": []
}{}
想要的输出:
{
"Profiles": [{}]
}
任何帮助将不胜感激
【问题讨论】:
-
不以a追加模式打开文件应该可以。
-
您以“追加”模式打开文件。这就是为什么您第二次运行脚本时 json 不正确的原因。更改您的“自动保存”功能。
标签: python json python-3.x list dictionary