在 Python 的文本文件中保存多个用户输入

Saving multiple user inputs in text file in Python

我是 Python 的新手,正在尝试这个项目。我需要将用户名和密码存储在文本文件中(以创建数据库)。我用过 pickle 模块。每次我 运行 代码时,我尝试过的代码都会删除以前存储的数据。

我知道我必须将数据附加到文件而不是写入文件,但我不知道如何操作。我怎样才能更正代码?

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

您似乎在此函数中使用了 "wb" 而不是 "ab",这导致文件在您每次要保存到文件时都被重置。此外,文件名应为 "UserDict",而不是 "UserText"

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