python - 我需要在 Python 中为我的登录系统读取一个 json 文件
问题描述
我正在努力阅读 json 文件并检查用户名是否已注册以及密码是否正确。我试着自己做,但是当用户名和密码在第一行时它才起作用。请帮忙:
import json
print("LoginSystem @mvtthis")
myRL = input("Login or Register?")
if myRL == "Register":
User = input("Username:")
PW = input("Password:")
PW1 = input("Confirm Password:")
if(PW == PW1):
print("Registration successfully.")
with open('LoginSystemData.json', 'a') as f:
f.write("\n" + User + "," + PW)
else:
print("Registration failed! Please confirm your Password correctly.")
if myRL == "Login":
User = input("Username:")
PW = input("Password:")
success = False
with open('LoginSystemData.json', 'r') as f:
for i in f:
a,b = i.split(",")
b = b.strip()
a = a.strip()
if(a==User and b==PW):
print("Login successful")
else:
print("Login failed. Wrong Username or Password.")
f.close()
break
解决方案
它对我有用:试试这个
...
if myRL == "Login":
User = input("Username:")
PW = input("Password:")
with open('LoginSystemData.json', 'r') as f:
readable = f.read() # --> you need to readable:str your file
lines = readable.splitlines() # --> ['name,pw','name,pw','name,pw']
user = list(filter(lambda l:l.split(',')[0] == User and l.split(',')[1] == PW,lines))
if user:
print("Login successful")
else:
print("Login failed. Wrong Username or Password.")
f.close()
实际上 filter() 像 for 循环一样:如果你想检查它:https ://www.w3schools.com/python/ref_func_filter.asp
推荐阅读
- ios - Swift UI 创建列表气泡效果
- java - JSON 解析器为 int 变量创建值为 0 的对象
- java - 如何使用 ZUUL 为多个服务处理 POST 请求
- gitkraken - 在 GitKraken 中提交。使摘要成为必填项
- ansible - anislble with_items with_nested 在角色任务内的循环中
- ios - 快速从一个模态 VC 转换到另一个模态 VC
- github - 如何向我只有他的电子邮件的人发送拉取请求
- c# - 尽管有全局范围,但 Unity 刚体拒绝存在
- css - SquareSpace 的 SASS Escape Calc
- microservices - 使用 Ribbon 和 Hystrix 自定义重试行为