即使输入正确,我的代码也拒绝验证输入的用户名和密码。
代码包含在下面;我哪里出错了吗?如果是,你能告诉我在哪里吗?
干杯。
import time
print ("Before playing, you must register.")
time.sleep(1)
username = open("username.txt","w+")
password = open("password.txt","w+")
print ("Please enter your desired username.")
username_input = input("> ")
print ("Please enter your desired password.")
password_input = input("> ")
username.write(username_input)
password.write(password_input)
username.close()
password.close()
time.sleep(1)
print ("Now, we must authenticate your username and password.")
time.sleep(0.5)
print ("Please input your username.")
u_input = input ('> ')
print ("Please input your password.")
p_input = input ('> ')
username.open("username.txt","r")
password.open("password.txt","r")
u_contents = username.read()
p_contents = password.read()
if u_input == u_contents:
print ("Username authenticated.")
if p_input == p_contents:
print ("Password authenticated.")
else:
print ("Incorrect username or password.")
username.close()
password.close()
即使您调用了write()
,内容实际上还没有写入。直到文件关闭(或刷新(或程序退出,文件内容才会写入磁盘。
写入文件后关闭它们。
由于某些原因,w+
无法工作。我发布了完整的工作代码,我已经更改了你的代码。将with/as
与open()
导入时间一起使用总是很有用的
import time
print ("Before playing, you must register.")
time.sleep(1)
print ("Please enter your desired username.")
username_input = input("> ")
print ("Please enter your desired password.")
password_input = input("> ")
with open('username.txt', 'w') as u:
u.write(username_input)
u.flush()
u.close()
with open('password.txt', 'w') as p:
p.write(password_input)
p.flush()
p.close()
time.sleep(1)
print ("Now, we must authenticate your username and password.")
time.sleep(0.5)
print ("Please input your username.")
u_input = input ('> ')
print ("Please input your password.")
p_input = input ('> ')
username=''
password=''
with open('xx.txt', 'r') as u:
username = u.read()
u.close()
with open('xxx.txt', 'r') as p:
password = p.read()
p.close()
if u_input == username:
print ("Username authenticated.")
if p_input == password:
print ("Password authenticated.")
else:
print ("Incorrect username or password.")
输出:
C:UsersDocuments>py test.py
Before playing, you must register.
Please enter your desired username.
> mike
Please enter your desired password.
> mike123
Now, we must authenticate your username and password.
Please input your username.
> mike
Please input your password.
> mike123
Username authenticated.
Password authenticated.