python - Python:如何将文件上下文与用户输入进行比较
问题描述
我有一个 Register.txt 文件,我在其中输入所有用户信息,例如用户名、电子邮件和密码。内容写入文件如下:
> emailadress, username, password;
那是我的代码:
import os
script_dir = os.path.dirname(__file__)
rel_path = 'Register.txt'
abs_file_path = os.path.join(script_dir, rel_path)
print('Welcome')
ExistingUser = input('Do you already have an Account y/n?: ')
def add_user(email, username, password):
file = open(abs_file_path, 'a')
file.write('> ' + email + ', ' + username + ', ' + password + ';\n')
file.close()
def check_password(userPassword, userName):
file = open(abs_file_path, 'r')
file_contents = file.read()
password = userPassword
Flag = 0
for i in file_contents.split('\n'):
if password == i:
Flag = 1
if Flag == 1:
print('Welcome back, ', userName)
else:
print('Something went wrong.')
if ExistingUser.lower() == 'n':
while True:
userEmail = input('email: ')
userName = input('username: ')
userPassword = input('password: ')
userPasswordConfirm = input('Confirm password: ')
if userPassword == userPasswordConfirm:
add_user(userEmail, userName, userPassword)
ExistingUser = 'y'
break
print('Passwords does NOT match!')
print('You have successfully registered!')
if ExistingUser.lower() == 'y':
while True:
userName = input('username: ')
userPassword = input('password: ')
check_password(userPassword, userName)
我的输出在登录部分看起来总是这样:Something went wrong
解决方案
如果文件中的每一行看起来像这样
>>> line = '> emailadress, username, password;'
在进行比较之前,您需要将其分成三个部分。首先删除开头和结尾的不需要的字符。
>>> line = line[2:-1]
>>> line
'emailadress, username, password'
然后用逗号分割线。
>>> email,uname,password = line.split(', ')
>>> uname, password
('username', 'password')
>>> uname == 'username' and password == 'password'
True
>>>
推荐阅读
- java - Quarkus Swagger-UI 授权
- docker - blackbox 导出器是否支持 telnet 探测?
- windows - 我如何读取另一个线程的 cpu 寄存器状态?(视窗)
- photoshop-script - 选择在 Photoshop Scripts 中保存文件的位置
- android-studio - 缩放保存在 android 设备上的图像
- python - 如何从 REST API 下载 JSON 数据集
- python - 有什么解决方案可以解决这个问题吗?
- google-bigquery - 使用 Python API 客户端在 BigQuery 中上传 UDF
- bash - Bash 脚本不会在输入命令时退出
- r - 将函数应用于数据框所有列的每列因子