0

I made a User login system in which user must enter one of three alphabets that is x to stop the program, y if you are a new user and n if you are not a new user.

self.register = input('Enter y if you have register or n if you are new or x to quit:')

If user enter's 'n' then it will create a new user and store it into a dictionary:- ex:- username = Fread password = hello

{'Fread':'hello'}

From here if user enter's y then it will check if te user exist with this condition:-

        self.existing_Id = input('Please enter your existing id here:')
        self.existing_Password = input('Please enter your existing password here:')
        if self.existing_Id in self.save and self.save[self.id] == self.password:
            print('you have successfully logged in')
        else:
            print('user not found please try again')

Also if the user already exist then it will also not create a user:-

        while True:
        self.id = input('please enter your ID here:')
        if self.id in self.save:
            print('User already exist!!!')
            break

Here i am trying to save all the username and password into file then everytime i stop and rerun te code again it should load all the previous saved file into a dictionary?

1 Answers1

0

What you're trying to do is called serialization : Turning python objects into things you can write into files, and back into python objects.

Python has some built in capabilities in the form of pickles :

from pathlib import Path
import pickle

SAVE_FILE = Path('some/path/file.pickle')

def save_state(state_dict):
    pickle.dump(state_dict, SAVE_FILE)

def restore_state():
    return pickle.load(SAVE_FILE)

In this example, you can use the save_state function before exiting the program to write your data to some/path/file.saved, and load_state when you open to read data.

Note that pickling has some security issues if the saved state file will be handled by someone malicious. In those circumstances, you could do a similar job with the JSON module, albeit with a little less leway with the data structures you could store in the file.

import JSON
from pathlib import Path

SAVE_FILE = Path('some/path/file.json')

def save_state(state_dict):
    JSON.dump(state_dict, SAVE_FILE)

def restore_state():
    return JSON.load(SAVE_FILE)
A-y
  • 793
  • 5
  • 16