Python 我需要通过检查外部文本文件中是否有用户名来验证用户名
问题是我检查外部文件的方法不起作用。几乎所有这些都不起作用,这只是我游戏的一部分Python 我需要通过检查外部文本文件中是否有用户名来验证用户名,python,Python,问题是我检查外部文件的方法不起作用。几乎所有这些都不起作用,这只是我游戏的一部分 file = open("users.txt","w") file.write("ali/n") file.write("mike/n") file.write("guy/n") file.close() def login(): username = input ("enter username") **for line in open("users.txt","r").readlines():
file = open("users.txt","w")
file.write("ali/n")
file.write("mike/n")
file.write("guy/n")
file.close()
def login():
username = input ("enter username")
**for line in open("users.txt","r").readlines():
while username not in users.txt:**
print("incorrect")
username = input ("enter username ")
print ("correct")
试试这个
def login():
username = input("enter username ")
users = [x.strip() for x in open("users.txt","r").readlines()]
while username not in users:
print("incorrect")
username = input("enter username ")
print ("correct 1")
您可以尝试以下方法:
def login():
username = input ("enter username")
users = open("users.txt","r").readlines()
users = [x.rstrip('\n') for x in users] # remove newline for each user in users
while username not in users: # check if entered username is in text file
print("incorrect")
username = input ("enter username ")
print("correct")
它仍然会出现以下错误消息文件“main.py”,第3行users=open(“users.txt”,“r”)。readlines():^SyntaxError:invalid syntaxWhoops,我把冒号留在那里了。我现在修复了错误消失了,但即使用户名在文件中,它也会一直打印不正确。你说不工作是什么意思?你得到了什么结果?有什么东西可以打印出来吗?我认为您可能无法获得预期结果的原因是,从文本文件读取的字符串最后有“\n”。和
while
语句可能无法执行,因为while部分出现错误。如果您可以建议一种不同的方法来验证用户名,而不使用/n,那么它可以工作,但现在两者之间没有分离usernames@Ali,那里没有分离?在文本文件中?您可以在文本文件中分隔名称,我建议的代码只是从数组中的字符串中删除换行符,以检查它们是否与输入的字符串匹配。当文本文件中的每个用户名后面都有/n时,它不起作用,但当我创建文件并省略/n时,例如file.write(“ali”)而不是file.write(“ali/n”)它的作品,但只有当有一个名字在文件中,我不知道你在做什么不正确,然后,我尝试了这段代码自己,它的作品为我它一定是一个问题,我的第一次制作的文件。我会在下一篇评论中发送它