我正在嘗試使用文本檔案在 python 中創建一個基本的注冊和登錄系統。我還希望程式一次性運行,這意味著我希望用戶能夠注冊,然后立即繼續登錄,而不是讓他們回傳并再次運行代碼。但是,我撰寫的代碼由于某種原因無法做到這一點。我在注冊功能的末尾添加了“signin()”,以允許用戶在成功注冊后繼續登錄,但這樣做會引發錯誤。相反,我必須再次運行代碼才能識別新注冊。
這是代碼:
def signin():
q = 0
user = input('Username: ')
password = input('Password: ')
with open('username.txt', mode='r')as names:
for i in names:
foundname = names.readlines()
with open('password.txt', mode='r')as passwords:
for j in passwords:
foundpass = passwords.readlines()
if user "\n" in foundname: # ReadLines() adds newlines
user_num = foundname.index(user "\n")
for i in range (0,user_num):
if password "\n" == foundpass[i]:
print("Login Successful.")
print("Incorrect Password. Try Again.")
signin()
else:
print("Username not found. Try again")
signin()
def signup():
with open('username.txt', mode='a')as names:
print("Please provide the following details to sign up")
name = str(input("Username: "))
names.write(f"{name}\n")
with open('password.txt', mode='a')as passwords:
password = (input("Password: "))
passwords.write(f'{password}\n')
print("signup successful. You can sign-In Now.")
signin()
signup()
這是輸出和我不斷收到的錯誤:
Please provide the following details to sign up
Username: abcdef
Password: password1
signup successful. You can sign-In Now.
Username: abcdef
Password: password1
Traceback (most recent call last):
File "D:/student.py", line 34, in <module>
signup()
File "D:/student.py", line 33, in signup
signin()
File "D:student.py", line 14, in signin
if password "\n" == foundpass[i]:
IndexError: list index out of range
Process finished with exit code 1
但是當我再次運行代碼時,我上次注冊時使用的憑據似乎有效。
Please provide the following details to sign up
Username: jkl
Password: mno
signup successful. You can sign-In Now.
Username: abcdef
Password: password1
Login Successful.
提前非常感謝!
uj5u.com熱心網友回復:
with open('password.txt', mode='a')as passwords:
...
signin()
檔案未關閉,您嘗試登錄,因此檔案指向最后一個索引,您無法讀取任何資料。將其更改為
with open('password.txt', mode='a')as passwords:
password = (input("Password: "))
passwords.write(f'{password}\n')
print("signup successful. You can sign-In Now.")
signin()
應該解決這個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/436103.html
