首页 > 解决方案 > 如何在不使用相同用户名两次的情况下将用户名存储在 txt 文件中?

问题描述

user = input("\nInput user's Login ID: ")
while True:
    password = str(input ("Input user's Password: "))
    rpass = str(input("Re-enter the Password: "))
    if password == rpass:
        file = open("username.txt", "a")
        file.write (user)
        file.close()
        break
    else:
        print("You have entered the wrong password, Try Again")

我想制作一个程序,用户可以使用他们的用户名和密码进行注册,并且可以将其存储到 txt 文件中。下一个要注册的人将无法使用相同的用户名。

我更新了代码,但发生了同样的问题,没有检测到以前的用户名。

仍然无法检测到

标签: pythonfileauthenticationpasswords

解决方案


每次写入文件时,它都会附加到同一行。

if data == user+ ":" +password:

结果,这种情况永远不会成立。

一种可能的解决方案是在每次写入后添加 \n 。

file.write (user +" : "+ password +"\n")

你的条件是

if data == user+ " : " +password:

注意空格和其他字符。它应该与此方法完全匹配。

编辑:您正在检查新用户名和密码是否匹配。您应该做的是将用户与data.split(':')[0][:-1]-

if data.split(":")[0][:-1] == user

这将收集字符串直到 ':' 并截断尾随空格。


推荐阅读