Home > Mobile >  How to check user input from a file in Python?
How to check user input from a file in Python?

Time:01-02

Hello I have a txt file that looks like this:

name1, password1
name2, password2,
name3, password3,
and so on...

I need to check if the user enters a name and password are the same stored in this file. I looked at this answers but they did not help: answ1 answ2 This is my code. If I put the correct name and password, the while loop still prompts me for user input:

name = input('Enter username: ')
password = input('Enter password: ')


with open('file.txt','r') as f: 
    data = f.readlines()
        
    for line in data:
        names =line.split(' ')[0]
        passwords = line.split(' ')[1]
      
        while name not in names or password not in passwords:
            name = input('Enter a valid username: ')
            password = input('Enter a valid password: ')

CodePudding user response:

For now you're testing the user input against EVERY line: the inputs can't match every lines

You'd better store the pairs in a dict, that'll facilitate the verifications


Test both at once

with open('file.txt', 'r') as f:
    data = f.readlines()

credentials = {}
for line in data:
    name, password = line.strip().split(",")
    credentials[name] = password

name = input('Enter a username: ')
password = input('Enter a password: ')
while name not in credentials or credentials[name] != password:
    name = input('Enter a valid username: ')
    password = input('Enter a valid password: ')

Separate tests

name = input('Enter a username: ')
while name not in credentials:
    name = input('Enter a valid username: ')

password = input(f'Enter a password for user {name}: ')
while credentials[name] != password:
    password = input(f'Enter a valid password for user {name}: ')

CodePudding user response:

Due to the inconsistent use of commas in the data file, you'll need to take some extra steps.

with open('file.txt') as indata:
    DB = dict(map(lambda e: e.rstrip(','), line.split()) for line in indata)
    while True:
        name = input('Enter username: ')
        password = input('Enter password: ')
        if DB.get(name) == password:
            break # username / password is valid
        print('Invalid username or password\a')

CodePudding user response:

With the help of fileinput. input() method, we can get the file as input and to can be used to update and append the data in the file by using fileinput. input() method. Return : Return the data of the file

  • Related