如何在txt文件中存储用户名,而不必使用相同的用户名两次?

2024-09-27 21:31:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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文件。下一个要注册的人将不能使用相同的用户名

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

still can't be detected


Tags: thetxtidtrueinputloginpassword用户名
2条回答

如果要使用parse模块,可以运行pip install parse并使用以下代码:

import parse

pattern = '{[a-z][A_Z][0-9]} : {[a-z][A_Z][0-9]}'
lines = []
user = input ("enter username: ")
password = input ("enter password: ")
with open('username.txt', 'r') as f:
   line = f.readline()

   while line:
       u, p = parse.parse(pattern, line)
       lines.append((u, p))
       line = f.readline()

users = [ u for (u, p) in lines ]

if user in users:
   print(f'Username {user} is taken, please try again.')

else:
   with open('username.txt', 'a') as f:
      f.write(f'{user} : {password}')
      print(f'Username and password successfully created.')

this is the output

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

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

因此,这种情况永远不会成立

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

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

你的情况会是

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

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

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

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

这将收集字符串直到“:”并截断尾随空间

相关问题 更多 >

    热门问题