将键和值附加到json文件

时间:2019-10-20 12:41:51

标签: python json

我正在创建一个用户系统。我需要将用户名和密码存储在文件中。

情况1:如果现有用户= 我需要阅读用户名和密码来检查现有用户。 我需要检查密码是否与键入值和字典值匹配。

情况2:如果新用户= 我需要检查用户名是否已存在于数据库中。 如果不是这样,我需要在不覆盖现有文件的情况下添加用户名和密码。

这里的问题,我在这里使用了json,但似乎覆盖了现有的字典。

我尝试写入一个简单的文本文件,在读取文件时以及在情况2中检查用户名是否存在时遇到问题。

# Login System Management
import json


class LoginSystem:
    def __init__(self):  # Opening and reading the registered users json.file
        self.users = json.load(open("Users.json"))
        self.login_screen()

    def login_screen(self):  # Log on screen to verify new or old user.
        while True:
            main_log = input("Are you new user?\n[Y]es or [N]o: ")
            if main_log == "Y":
                self.new_user()
                break
            elif main_log == "N":
                self.old_user()
                break
            else:
                print("Invalid answer.\n")

    def old_user(self):  # Log in screen if old user.
        while True:
            user_id = input("Please enter your user id: ")
            user_password = input("Please enter your password: ")
            if len(user_id) <= 64 and len(user_password) <= 64 and self.check_system(user_id, user_password):
                print("Logging In")
                break
            else:
                print("Wrong password or username!\n")

    def check_system(self, name, password):  # Checking system to verify old user id and password.
        data = self.users
        try:
            expected_password = data[name]
        except KeyError:
            return False
        if password != expected_password:
            return False
        return True

    def new_user(self):  # Log in screen if new user.
        while True:
            print("\nMax Length is 64 chars.")
            reg_id = input("Register your username: ")
            reg_password = input("Key in password: ")
            if len(reg_id) <= 64 and len(reg_password) <= 64:
                if reg_id not in self.users:
                    print("Loading.....")
                    self.update_database(reg_id, reg_password)
                    print("Registered Successfully.")
                    break
                else:
                    print("User already registered!\n")
                    self.old_user()
                    break
            else:
                print("Error. Max Length is 64 chars.\n")

    def update_database(self, new_user_name, new_user_password):  # Writing new username and password to json.file
        new_username = new_user_name
        new_password = new_user_password
        field = [new_username, new_password]
        with open("Users.json", "w") as f:
            json.dump(field, f)


check = LoginSystem()

2 个答案:

答案 0 :(得分:0)

我已经找到答案了。如果有人想推荐您可以关注。

首先,我创建了一行username,password行的csv文件,并将其保存在同一目录中。

其余代码如下。

     # Login System Management import csv import time

     class LoginSystem:

         def __init__(self):  # Opening
             self.login_screen()

         def login_screen(self):  # Log on screen to verify new or old user.
             while True:
             main_log = input("Are you new user?\n[Y]es or [N]o: ")
             if main_log == "Y":
                 self.new_user()
                 break
             elif main_log == "N":
                 self.old_user()
                 break
             else:
                 print("Invalid answer.\n")

         def old_user(self):  # Log in screen if old user.
             while True:
                 user_id = input("\nPlease enter your user id: ")
                 user_password = input("Please enter your password: ")
                 if len(user_id) <= 64 and len(user_password) <= 64 and self.read_database(user_id, user_password):
                     print("Successful")
                     break
                 else:
                     print("Wrong password or username!\n")

         def new_user(self):  # Log in screen if new user.
             print("\nMax Length is 64 chars.")
             reg_id = input("Register your username: ")
             if self.check_database(reg_id) is True:
                 while True:
                     reg_password = input("Key in password: ")
                         if len(reg_id) <= 64 and len(reg_password) <= 64:
                             print("Loading.....")
                             time.sleep(2)
                             self.update_database(reg_id, reg_password)
                             print("Registered Successfully.")
                             break
                         else:
                             print("Error. Max Length is 64 chars.\n")
            else:
                print("User Already Exists.\n")
                self.old_user()

         def read_database(self, name, password): # Checking if password match to username
             with open("Users.csv", "r") as f:
                 reader = csv.reader(f)
                 user_list = {}
                 for row in reader:
                     user_list[row[0]] = row[1]
                 try:
                     expected_password = user_list[name]
                     if password == expected_password:
                     print("Logging In")
                     time.sleep(2)
                     return True
                 except KeyError:
                     return False
                 if password != expected_password:
                     return False

         def check_database(self, new_name): # Checking if new id exists in user database
             with open("Users.csv", "r") as f:
                 reader = csv.reader(f)
                 user_list = {}
                 for row in reader:
                     user_list[row[0]] = row[1]
                 if new_name in user_list.keys():
                     return False
                 elif new_name not in user_list.keys():
                     return True

         def update_database(self, new_user_name, new_user_password):  # Writing new username and password to file
             with open("Users.csv", "a", newline="\n") as f: # appends the new username and password to new row of line
                 writer = csv.writer(f)
                 writer.writerow([new_user_name, new_user_password])


    check = LoginSystem()

答案 1 :(得分:0)

问题是您正在以“写入”模式打开csv文件。此模式用新行替换到目前为止您在数据库中编写的内容。请改用“附加”。

with open("Users.json", "a") as f: