简体   繁体   English

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

[英]Saving multiple user inputs in text file in Python

I am fairly new to Python and am trying this project.我对 Python 相当陌生,并且正在尝试这个项目。 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.我知道我必须将 append 数据写入文件而不是写入文件,但我不知道如何。 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()

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.看来您在此 function 中使用的是"wb"而不是"ab" ,这导致文件在您每次希望保存时都会重置。 Also, The filename should be "UserDict" , instead of "UserText" .此外,文件名应该是"UserDict" ,而不是"UserText"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM