python - 如何在不使用相同用户名两次的情况下将用户名存储在 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 文件中。下一个要注册的人将无法使用相同的用户名。
我更新了代码,但发生了同样的问题,没有检测到以前的用户名。
解决方案
每次写入文件时,它都会附加到同一行。
if data == user+ ":" +password:
结果,这种情况永远不会成立。
一种可能的解决方案是在每次写入后添加 \n 。
file.write (user +" : "+ password +"\n")
你的条件是
if data == user+ " : " +password:
注意空格和其他字符。它应该与此方法完全匹配。
编辑:您正在检查新用户名和密码是否匹配。您应该做的是将用户与data.split(':')[0][:-1]
-
if data.split(":")[0][:-1] == user
这将收集字符串直到 ':' 并截断尾随空格。
推荐阅读
- node.js - MongoDB NodeJS 驱动程序池连接(问题)
- flutter - 无法在 FCM onBackgroundMessage (Flutter) 中使用任何插件
- ns-3 - 将 NS3 示例 tcp-variants-comparison.cc 源代码节点升级为无线节点
- kubernetes - 开始使用 keycloak 和 kubernetes
- excel - 添加工作表并重命名该工作表的代码
- r - 将 R 脚本连接到 Spotfire TERR 表达式函数
- c - 如何比较字符串指针?
- java - 带有 Mockito 单元测试和 Servlet 请求的过滤器链
- android-room - Android Kotlin Room 代码实验室中 getTonightFromDatabase() 的目的是什么?
- c++ - 为什么有些 ARRAYS 用 C++ 写成这样?