即使输入正确,我的代码也拒绝验证输入的用户名和密码。
以下包含代码;我在哪里出错了?如果是这样,您能告诉我在哪里吗?
干杯。
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()
答案 0 :(得分:2)
即使您调用了write()
,内容实际上尚未被写入。在文件关闭(或刷新)或程序退出之前,文件内容不会写入磁盘。
在写入文件后关闭文件。
答案 1 :(得分:0)
由于某些原因,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:\Users\Documents>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.