簡體   English   中英

從文本文件檢查字典鍵值

[英]Checking Dictionary Key Value from Text File

這里是 Python 初學者,我正在嘗試創建一個登錄系統(使用 Python 3)。 我創建了一個函數來將用戶的用戶名和密碼作為字典 {uname:pswd} 存儲在文本文件中。 我創建了另一個允許用戶登錄的函數,但我不知道如何檢查他們的詳細信息是否與文本文件中的字典鍵及其相應值匹配。

這是我到目前為止所做的:

def user_login(): #login function
    uname=input("Enter username:")
    pswd=input("Enter password:")
    d={uname:pswd}
    loginfile=open('logindata.txt', 'r')
    with loginfile as f:
        for line in f:
            if d.get(uname)==pswd: #should check user input matches dictionary in text file
                return "Accepted"
            else:
                return "Wrong username/password"
    loginfile.close()

有了這個,我收到一條錯誤消息: AttributeError: 'str' object has no attribute 'get' 它將它作為一個字符串讀取,那么我如何獲得將它作為字典讀取的代碼? 另外,作為新手,我很確定我的代碼的某些部分可能是錯誤的。 關於我應該修復什么的任何建議?

我執行您的相同代碼並且沒有出錯,但是無論您輸入什么作為憑據,它們總是被接受。 這是解決您問題的方法

def user_login():  # login function
    uname = input("Enter username:")
    pswd = input("Enter password:")
    d = {uname: pswd}

    with open('logindata.txt', 'r') as f: # here I open logindata.txt in read mode and I call it f
        credentials = f.read().split('\n') # I make a list with the credentials by splitting the lines of the file (I think your file has 2 lines: username and password)
        check_dict = {credentials[0]: credentials[1]} # I create the dictionary with the credentials

    if d.get(uname) == check_dict.get(credentials[0]):  # check if the input username and password (d dictionary) are the same as those stored in the logindata.txt file
        return "Accepted"
    else:
        return "Wrong username/password"

問題是您的代碼檢查d字典中uname的值是否等於pswd ,但是當您聲明字典d={uname:pswd}您將pswd的值分配給uname ,因此它們將始終是相同的。 我還使用with open('logindata.txt', 'r') as f:而不是loginfile=open('logindata.txt', 'r') with loginfile as f: ... loginfile.close()因為是只是一種打開文件的更好方法,而且您必須鍵入更少的代碼。 無論如何,我建議不要使用字典而只是這樣做

def user_login():  # login function
    uname = input("Enter username:")
    pswd = input("Enter password:")

    with open('logindata.txt', 'r') as f: # here I open logindata.txt in read mode and I call it f
        credentials = f.read().split('\n') # I make a list with the credentials by splitting the lines of the file (I think your file has 2 lines: username and password)

    if uname == credentials[0] and pswd == credentials[1]: # check if input credentials are the same as stored credentials
        return "Accepted"
    else:
        return "Wrong username/password"

如果這些代碼都不起作用,我建議包括在logindata.txt中存儲憑據的函數 如果您需要幫助才能有多個帳戶登錄,您一定要添加該功能。 希望這解決了你的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM