[英]csv - Creating a login system, python not properly reading from .csv file?
我試圖制作一個基本循環的登錄系統,每當我嘗試輸入正確的詳細信息(甚至存儲在.csv文件中)時,無論我輸入什么內容,它都會輸出為錯誤的用戶名/密碼。 這段代碼適用於python 3.6,但是我需要它才能適用於python 3.2.3。
loop1 = False #for this bit of code (logging in)
loop2 = False #for next bit of code
while loop1 == False:
choice = input("Login/SignUp [TYPE 'L' OR 'S']: ").lower()
if choice == "l":
username = input("Username: ")
password = input("Password: ")
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
#this whole bit of code is meant to read from the csv and check if the login details are correct
else:
print("Username/Password [INCORRECT]")
您可能在line.split(',')中存在錯誤,請嘗試使用line.strip()。split(',')
TL; DR:在那發布了一個正確的解決方案: https : //github.com/cgte/stackoverflow-issues/tree/master/47207293-csv-dict
如有需要,我將在后面補充我的答案。
此外,您在這里的代碼設計不佳,並且發現自己在循環中間進行調試。
因此,首先:加載數據文件,將內容存儲到字典中。
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
應該成為
user_pass = {}
f = open("usernamepassword.csv","r")
for line in f:
user, password = line.strip().split(",")
user_pass[user] = password
f.close()
或更好
with open("usernamepassword.csv","r") as f:
for line in f.readlines():
user, password = line.split().split(",")
user_pass[user] = password
最終運行python -i yourfile.py並鍵入“ user_pass”,以查看正確存儲進一步代碼后實際存儲的內容。
考慮使用csv模塊: https : //docs.python.org/3/library/csv.html
然后從輸入中獲取用戶名和密碼並檢查:
if login in user_pass and user_pass[login] = password:
# or better `if user_pass.get(login, None) == password:`
do_stuff()
請允許我重構您的代碼:
def login(username, password):
with open("usernamepassword.csv", "r") as csv:
all_details =
[[attr.strip() for attr in line.split(",")]
for line in csv]
return any(
username == details[0]
and password == details[1]
for details in all_details)
def login_action():
username = input("Username: ")
password = input("Password: ")
if not login(username, password):
raise ValueError("Username/Password [INCORRECT]")
return True
_USER_ACTIONS = {
'l': login_action
}
def main():
while True:
choice = input("Login/SignUp [TYPE 'L' or 'S']: ").lower()
action = _USER_ACTIONS[choice]
try:
if action():
break
except Exception as err:
print(err.message)
我認為您的意外行為是由於不剝離除以之后的值,
通過更換來解決:
if username == details[0] and password == details[1]:
帶有:
if username == details[0] and (password+"\n") == details[1]:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.