Search code examples
pythonpython-3.xdictionarypicklebinaryfiles

Saving multiple user inputs in text file in Python


I am fairly new to Python and am trying this project. I need to store usernames and passwords in a text file ( to create a database). I have used the pickle module. The code I've tried erases previously-stored data every time I run the code.

I have understood that I have to append data to the file instead of writing to it but I don't know how. How can I correct the code?

import pickle
# pickle mod converts obj into byte stream to store in database
import time

def load_Dictionary():
    try :
        with open("UserDict.txt" , "rb") as ufile :
            return pickle.load(ufile)
    except IOError :
        with open("UserDict.txt" , "ab") as ufile :
            pickle.dump(dict() , ufile)
            return dict()

def save_Dictionary(UserDict):
    with open("UserText.txt" , "wb") as ufile :
        pickle.dump(UserDict , ufile)

def new_User_Login():
    userDict = load_Dictionary()  # dictionary is loaded
    checkUserAcc = input("Are you a new user ( Yes or No ) ? ")
    # insert buttons for yes no
    # tk.Button(window, text="", command=password_generator).pack(pady=10)

    if (checkUserAcc == "Yes" or checkUserAcc == "yes" or checkUserAcc == "YES"):
        username = input("Please enter your username : ")
        Root_password = input ("Please enter your password :")
        if ( username in userDict):
            print("Username you entered is not available")
            new_User_Login()
        else :
            userDict[username] = Root_password
            print("Login Successful!")
            save_Dictionary(userDict)  # saves new login info
            time.sleep(2.0)

    elif (checkUserAcc == "No" or checkUserAcc == "no" or checkUserAcc == "NO") :
        user_login()

    else :
        print("Invalid input! Try Again.")
        new_User_Login()

def user_login():
    global username
    global Root_password
    global tries
    login_Username = input("Enter your Username : ")
    login_Password = input("Enter your Password : ")
    UserDict = load_Dictionary()
    if ( tries < 5):
        for key in UserDict:
            if (login_Username == key and login_Password == UserDict[key]):
                print("You have successfully logged in !")

            else :
                print("Login Failed! Please try again")
                tries = tries + 1
                user_login()

            if( tries >= 5 ):
                print("You have attempted login too man times. Try again later. ")
                time.sleep(30.0)
                tries = 1    # reset tries counter
                user_login()

global tries
tries=1
new_User_Login()

Solution

  • It appears you were using "wb" instead of "ab" in this function, which caused the file to reset everytime you wished to save to it. Also, The filename should be "UserDict", instead of "UserText".

    def save_Dictionary(UserDict):
        with open("UserDict.txt" , "ab") as ufile:        
            pickle.dump(UserDict , ufile)