[英]How does the python socket.recv() method know that the end of the message has been reached?
[英]How to know when the bottom of the text file has been reached
因此,我有一個文本文件,其中包含程序用戶的詳細信息。
在我的程序中,我有一個登錄系統,該系統從該文本文件中檢索數據,但是我不知道如何知道何時到達末尾。
文本文件中的數據示例如下所示:
鮑勃,鮑勃15,足球,15
我的代碼如下所示:
username = input("Enter username: ")
password = input("Enter password: ")
file = open("userDetails.txt", "r")
match = False
while match == False:
finished = False
while finished == False:
for each in file:
each = each.split(", ")
realUser = each[1]
realPass = each[2]
if realUser == username and realPass == password:
match = True
finished = True
print("match")
elif each == "":
finished = False
username = input("Re-enter username: ")
password = input("Re-enter password: ")
match = False
else:
finished = False
我不確定的部分是elif each == "":
部分。
有任何想法嗎?
鑒於這個問題,我相信在這里使用for-else
子句將是理想的。
注意 : for
循環的else
子句在循環正常退出(即未遇到break
語句)時執行。
算法
1.要求用戶輸入
2.最初將標志match
設置為False
3.在文件中搜索,直到找到匹配項。
4.使用上下文管理器打開文件; 確保操作后關閉文件。
5.一旦找到匹配項,將標志match
設置為True
,就跳出文件循環。
6.如果未找到匹配項,請要求用戶重新輸入憑據並再次執行搜索操作。
7.繼續直到找到匹配項。
碼
username = input("Enter username: ")
password = input("Enter password: ")
match = False
while not match:
with open("userDetails.txt", "r") as file:
for line in file:
user_data = line.split(",")
real_user, real_pass = user_data[1].strip(), user_data[2].strip()
if username == real_user and password == real_pass
print('Match')
match = True
break
else:
username = input("Re-enter username: ")
password = input("Re-enter password: ")
提示 :您也可以嘗試為CSV模塊讀取Python中的數據文件。
當到達文件末尾以結束循環時,正確的代碼是:
file = open("userDetails.txt", "r")
match = False
while match == False:
for each in file:
each = each.split(", ")
realUser = each[1]
realPass = each[2]
if realUser == username and realPass == password:
match = True
print("match")
elif each == "":
username = input("Re-enter username: ")
password = input("Re-enter password: ")
match = False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.