【发布时间】:2018-02-10 16:33:39
【问题描述】:
如何在下面的代码中注册用户名和密码时,它会在 txt 文件中添加一个新行,当你登录时,它会单独检查 txt 文件中的每一行 如果任何一行与登录名匹配,则声明它是正确的,而不是检查用户名和密码是否与整个内容匹配
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for
register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","w")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","w")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
if usr == file.read():
print "Username correct"
file.close()
else:
print "Username incorrect or not registered"
file.close()
file = open("Password.txt","r")
if pss == file.read():
print "Password correct"
file.close()
else:
print "Password incorrect or not registered"
file.close()
【问题讨论】:
-
以附加模式打开(使用'a'而不是'w')将添加到文件的末尾。使用
file.readlines()获取文件中的行列表,然后使用循环检查每一行是否匹配。
标签: python python-2.7