我正在嘗試向用戶詢問用戶名和密碼,并檢查帶有用戶名和密碼的檔案,看看它是否存在,如果它沒有告訴用戶他輸入了錯誤的資訊,它只會說歡迎。該檔案只是一個簡單的文本檔案,格式為“用戶名,密碼”,如下所示
固態硬碟,adgEgd
aegag,asdhasdh
這是我的代碼
class Account():
def __init__(self, name, password):
self.name = name
self.password = password
username_input = input("Enter the name: ")
userpassword_input = input("Enter password: ")
file = open('account information.txt', 'r')
data = []
for lines in file:
temp = lines.split(',')
data.append(Account(temp[0], temp[1]))
file.close()
isExsits = ' '
for d in data:
if username_input == d.name and userpassword_input == d.password:
isExsits = 'huzzah'
print(isExsits)
它識別用戶名但不識別密碼
uj5u.com熱心網友回復:
密碼中有一個換行符,從檔案中讀取后看起來像 adgEgd\n。
你可以通過使用擺脫它 rstrip
data.append(Account(temp[0], temp[1].rstrip()))
uj5u.com熱心網友回復:
這按您的預期作業,它遍歷account_information.txt檔案中的所有帳戶并Account為每個帳戶創建一個物件,并將其添加到data串列中。
之后,我們遍歷每個帳戶并檢查用戶提供的憑據是否與串列中的任何憑據匹配。
class Account():
def __init__(self, name, password):
self.name = name
self.password = password
username_input = input("Enter the name: ")
userpassword_input = input("Enter password: ")
data = []
with open("account_information.txt") as file:
for line in file.readlines():
credentials = line.rstrip().split(",")
data.append(Account(credentials[0], credentials[1]))
accountExists = False
for account in data:
if (account.name == username_input) and (account.password == userpassword_input):
accountExists = True
print(accountExists)
uj5u.com熱心網友回復:
它似乎像這樣作業正常,所以我同樣會說這可能是行尾的換行符或其他無關字符導致計算失敗。
user_pass_list = [
('SSD', 'adgEgd'),
('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgEgd'
exists = False
for d in user_pass_list:
if username == d[0] and password == d[1]:
exists = True
print(exists) # True
另一種方法可以是只做一個in檢查,這樣我們就不需要迭代user_pass_list,例如:
user_pass_list = [
('SSD', 'adgEgd'),
('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgegd' # casing is different
exists = (username, password) in user_pass_list
assert exists is False # True
使用Account原始問題中的類示例,重新格式化為資料類以獲得更清晰的代碼:
from dataclasses import dataclass
# same as `@dataclass(eq=True)`, so an equals (__eq__) method
# is automatically generated for the class.
@dataclass
class Account:
name: str
password: str
user_pass_list = [
Account('SSD', 'adgEgd'),
Account('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgEgd'
exists = Account(username, password) in user_pass_list
assert exists is True # True
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337969.html
