我正在開發一個使用while循環的 python 項目。獨特的東西。但是,我無法讓循環為我完成它的工作。我的代碼:with open("accounts.txt", "r") as account_file: while account == "": account = str(input("Enter a username: ") + " ") if account not in account_file.read(): print("That username was not found.") account = ""當我運行它時,它會提示我輸入用戶名,如果可以在其中找到我輸入的字符串(加上添加的空格),accounts.txt我將被告知可以找到我的用戶名。如果我輸入了一個無效的用戶名,程序應該會告訴我它找不到我輸入的用戶名然后讓我再試一次——除非我在下次嘗試時輸入正確的用戶名,程序仍然會告訴我我的用戶名找不到。我嘗試進行此更改:if account in account_file.read(): account = accountelse: print("That username was not found.") account = ""而且它仍然無法正常工作。誰能告訴我為什么?我只是在尋找一個簡單的解決方案。
1 回答

www說
TA貢獻1775條經驗 獲得超8個贊
我假設你想找到文件中用戶名所在的文件行。如果您對查找用戶名所在的特定行不感興趣,而只想繼續循環直到輸入有效的用戶名,那么您應該知道您只能在文件打開后調用一次read()。
考慮這樣做:
while account == "":
? ? account = str(input("Enter a username: ") + " ")
? ? with open("accounts.txt", "r") as account_file:
? ? ? ? if account not in account_file.read():
? ? ? ? ? ? print("That username was not found.")
? ? ? ? ? ? account = ""
如果您確實想要用戶名所在的行,您可能需要這樣的東西:
with open("accounts.txt", "r") as account_file:
? ? account = str(input("Enter a username: ") + " ")
? ? for line in account_file:
? ? ? ? if account in line:
? ? ? ? ? ? print("Found username")
? ? ? ? ? ? break
添加回答
舉報
0/150
提交
取消