我基本上是在创建一个联系人簿,我想在JSON上存储数据来练习它。我已经从字典中对允许它的代码进行了排序,但问题是,当我重新运行脚本时,另一个字典会附加到现有的字典中,创建两个额外的大括号,从而抛出错误"应为文件结尾">
这是代码:
import json
new_contacts = {}
def contacts():
while True:
name = input("Contact's name: ")
email = input("Email: ")
number = input("Phone number: ")
new_contacts[name] = {"email": email, "number": number}
"""cursor.execute(
'INSERT INTO contacts VALUES (?, ?, ?)',
(name, email, number)
)"""
restart_or_not = input("Continue? y/n ").lower()
if restart_or_not == "y":
print(new_contacts)
continue
else:
with open('contact_book.json', 'a') as file:
json.dump(new_contacts, file, indent=4)
break
contacts()
这是一个JSON的示例,它来自
{
"d": {
"email": "e",
"number": "3"
},
"h": {
"email": "y",
"number": "6"
},
"f": {
"email": "r",
"number": "3"
},
"n": {
"email": "j",
"number": "9"
}
}{
"g": {
"email": "j",
"number": "0"
}
}
前四个条目不会产生任何问题,因为它们是在同一次运行中附加的,但如果我退出程序并重新运行它(例如"g"(,那么新字典就会产生冲突。有什么建议吗?
一种方法是,在添加到文件之前,删除最后一个右括号}
,在转储之前,将dict强制转换为字符串,并使用此your_string[1:]
删除第一个括号。
我为您编码的另一种方式是,将json加载到一个变量中,添加新的输入,然后将其重新转储到文件中
import json
from os import path # it helps to check if file exists
new_contacts = {}
def contacts():
while True:
name = input("Contact's name: ")
email = input("Email: ")
number = input("Phone number: ")
new_contacts[name] = {"email": email, "number": number}
"""cursor.execute(
'INSERT INTO contacts VALUES (?, ?, ?)',
(name, email, number)
)"""
restart_or_not = input("Continue? y/n ").lower()
if restart_or_not == "y":
print(new_contacts)
continue
else:
# if the file doesn't exist, write an empty json object into it
# which will make it easier later to load data from
if not path.exists('contact_book.json'):
with open('contact_book.json', 'w+') as file:
json.dump({}, file)
# This loads the data into the variable dict called loaded_data
with open('contact_book.json', 'r') as file:
loaded_data = json.load(file)
for k, v in new_contacts.items():
loaded_data[k] = v
# redumps your data into the json file
with open('contact_book.json', 'w') as file:
json.dump(loaded_data, file, indent=4)
break
contacts()
刚刚更新了代码的其他部分。它检查文件是否存在。如果存在,则读取并更新文件的内容,然后将其转储到文件中。如果它不存在,您的旧代码将被执行。
if os.stat("contact_book.json").st_size != 0:
with open('contact_book.json', 'r+') as file:
contents = json.loads(file.read())
contents.update(new_contacts)
file.seek(0)
json.dump(contents, file, indent=4)
else:
with open('contact_book.json', 'a') as file:
json.dump(new_contacts, file, indent=4)
break
老实说,这不是一个有效的解决方案。但这应该能够引发一个想法。