如何创建一个python字典来存储多个帐户的用户名和密码 [英] How to create a python dictionary that will store the username and password for multiple accounts

查看:244
本文介绍了如何创建一个python字典来存储多个帐户的用户名和密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在遇到的问题是我的字典使用键:值来存储用户名:密码是每次我重新运行程序时,当前的键:值被重置,字典再次设置为空.我的程序的目标是让一个人使用用户名和密码登录并能够存储笔记和密码(我用 python .txt 文件做到了这一点).然后下一个人可以过来,创建一个帐户并执行相同的操作.这是我的代码(我已经注释了与我的问题有关的每一行代码):

The problem I have right now is that for my dictionary that uses a key:value to store username:password is that every time I rerun the program, the current key:value is reset and the dictionary is set to empty again. The goal of my program is to have a person log in with a username and password and be able to store notes and passwords (I did this with python .txt files). Then the next person can come along, create an account and do the same. Here is my code (I have commented every line of code pertaining to my problem):

def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
    userName = input("Please Set Your New Username: ")
    password = input("Please Set Your New Password: ")
//  if (userName in dictAcc):
        print("Username is taken")
        userPass()
    else:
//      dictAcc[userName] = password 
        print("Congratulations! You have succesfully created an account!")
        time.sleep(1.5)
        dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
    login()
else:
    print("Invalid answer, try again")
    userPass()


def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
//  for key in dictAcc:
//      if (loginUserName == key and loginPass == dictAcc[key]):
//          print("You have successfully logged in!")
            dataInput()
        else:
            print("Please try again")
            tries += 1
            login()
        if (tries >= 3):
            print("You have attempted to login too many times. Try again later.")
            time.sleep(300)
            login()

userPass()

推荐答案

正如其他人提到的,您需要将字典保存到文件中,并在重新启动程序时加载它.我调整了您的代码以使其适合我并创建了两个函数,一个用于保存字典 (savedict),另一个用于加载它 (loaddict).except IOError 部分只是为了在它不存在时创建一个新文件.

As others have mentioned, you need to have your dictionary saved into a file and load it when you restart your program. I adjusted your code to work for me and created two functions, one to save the dictionary (savedict) and another to load it (loaddict). The except IOError part is just so that it creates a new file if it doesn't exist.

请注意,一般来说,将密码存储在文本文件中是一个非常糟糕的主意.如果您尝试打开 "dictAcc.txt" 文件(它将包含所有密码),您可以清楚地看到原因.

Note that in general, storing passwords in a text file is a very bad idea. You can clearly see the reason why if you try to open the "dictAcc.txt" file (it will have all passwords there).

import pickle
import time

def loaddict():
    try:
        with open("dictAcc.txt", "rb") as pkf:
            return pickle.load(pkf)
    except IOError:
        with open("dictAcc.txt", "w+") as pkf:
            pickle.dump(dict(), pkf)
            return dict()

def savedict(dictAcc):
    with open("dictAcc.txt", "wb") as pkf:
        pickle.dump(dictAcc, pkf)


def userPass():
    dictAcc = loaddict() #Load the dict
    checkAccount = raw_input("Do you have an account (Y or N)?")
    if (checkAccount == 'N' or checkAccount == 'n'):
        userName = raw_input("Please Set Your New Username: ")
        password = raw_input("Please Set Your New Password: ")
        if (userName in dictAcc):
            print("Username is taken")
            userPass()
        else:
            dictAcc[userName] = password 
            print("Congratulations! You have succesfully created an account!")
            savedict(dictAcc) #Save the dict
            time.sleep(1.5)
            # dataInput() Code ends
    elif(checkAccount == 'Y' or checkAccount == 'y'):
        login()
    else:
        print("Invalid answer, try again")
        userPass()


def login():
    global userName
    global password
    global tries
    loginUserName = raw_input("Type in your Username: ")
    loginPass = raw_input("Type in your Password: ")
    dictAcc = loaddict() #Load the dict
    if (tries < 3):
        for key in dictAcc:
            if (loginUserName == key and loginPass == dictAcc[key]):
                print("You have successfully logged in!")
                # dataInput() Code ends
            else:
                print("Please try again")
                tries += 1
                login()
            if (tries >= 3):
                print("You have attempted to login too many times. Try again later.")
                time.sleep(3)
                tries=1 #To restart the tries counter
                login()

global tries
tries=1
userPass()

这篇关于如何创建一个python字典来存储多个帐户的用户名和密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆