我正在编写一个充当登录屏幕的简单程序。作为其中的一部分,我让用户创建一个帐户,该帐户将在 JSON 文档中保存他们的姓名、年龄、城市和登录信息。我已经能够很容易地写入 JSON,但是每当我从文件中读取时,它都会抛出“额外数据错误”并说它在第 2 行第 14 列
我正在使用 python 3.8.2,如果有帮助的话
这是中的代码main.py
import json
def read(accList):
with open('acc.json') as accountFile:
first = accountFile.read(1)
if not first:
print("No accounts")
else:
accList["account"]=json.load(accountFile)
accountFile.close()
return(accList)
def write(accList):
with open('acc.json',"w") as accountFile:
accountFile.write(json.dumps(accList, indent = 4, sort_keys=True))
accountFile.close()
def login(accList):
accList=read(accList)
user=input("Please enter your username: ")
password=input("Please enter your password: ")
def create(accList):
accList=read(accList)
name=input("Please enter your name: ")
age =input("How old are you: ")
city = input("What city do you live in: ")
user=input("Please create a username: ")
password=input("Please create a password: ")
accList["account"].append({
"name": name,
"age": age,
"city": city,
"username": user,
"password": password
})
write(accList)
def main():
accList = {}
accList["account"] = []
returning=input("Welcome to Cael's login screen.\nDo you already have an account? ")
if(returning.lower()=="yes"):
login(accList)
elif(returning.lower()=="no"):
create(accList)
#else:
# print("Sorry that's not a valid answer. Please only type \'Yes\' or \'No\'.")
main()
这是我在 JSON 中的输出(注意:添加一个帐户可以正常工作,但之后会抛出错误)
{
"account": [
{
"age": "52",
"city": "Jerome",
"name": "Maynard",
"password": "pass",
"username": "mjkeenan"
}
]
}
抱歉,如果这看起来有点愚蠢,或者存在明显的错误。我对整个 JSON 文件还是陌生的
尚方宝剑之说
相关分类