Visha2182
Visha2182

Reputation: 1

Append key and value to json file

I am making a user system. I need to store the usernames and passwords in a file.

Case 1: If existing user= I need to read the username and password to check existing user. I need to check if the passwords match from the keyed in value and from the dictionary value.

Case 2 : If new user= I need to check if the username already exist in the database. If not then, i need to append the username and password in existing file without overwriting.

The problem here, i have utilised json here but it seems to overwrite the existing dict.

I have tried writing to a simple text file and i encounter problem in case when reading the file and also when i check if username exists in case 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()

Upvotes: 0

Views: 51

Answers (2)

Yoana G
Yoana G

Reputation: 600

The problem is that you are opening the csv file in "write" mode. This mode replaces what you have written in the database so far with the new line. Use "append" instead.

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

Upvotes: 1

Visha2182
Visha2182

Reputation: 1

I had figure out the answer. If anyone wants to refer you can follow.

First, I have created a csv file with row of line username,password and save it in the same directory.

The rest as follows the code.

     # 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()

Upvotes: 0

Related Questions