首页 > 解决方案 > 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

标签: pythonpython-3.x

解决方案


如果文件中的每一行看起来像这样

>>> 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
>>>

推荐阅读