Haziq Hassan
Haziq Hassan

Reputation: 35

How to read specific words in lines?

I'm new to this and currently I'm trying to create a sign up and log in system for my assignment and I did this.

def signUp(): #USER SIGN UP
    name=(str(input("Name: ")))
    intake=(str(input("Intake: ")))
    hp=(str(input("Phone Number: ")))
    email=(str(input("E-mail: ")))
    tp=(str(input("Student ID: ")))
    pw=(str(input("Password: ")))
    OccupantsData=[name,intake,hp,email,tp,pw]
    file=open("Database.txt","a")
    file.write(str(OccupantsData)+"\n")
    file.close()

When I run this code, it'll save all the inputs into 'Database.txt' like this

    ['James', 'Jul17', '1234', '[email protected]', 'TP1234', 'password']

    ['Jon', 'Sep17', '5567', '[email protected]', 'TP2345', 'passwords']

    ['Han', 'Oct17', '7554', '[email protected]', 'TP5546', 'passwords1']

    ['Klye', 'Oct17', '2234', '[email protected]', 'TP0094', 'passwords2']

Now, i'm not sure how code the login... It should take in the TPnumber and make sure it matches the password on the line... When I code it this way, it only works for the TPnumber and password on the first line and it will not work for others...

def logIn(): #USER SIGN IN
    TP=str(input("Please input TP Number:"))
    password=input("Please input password:")
    f=open("Database.txt","r")
    user=f.read()
    if (TP) in user:
        if password in user:
            print("Welcome")
        else:
            print ("Username or Password doesn't match")
            logIn()
    else:
        print("Error")
        logIn()

What can I do to make it read the input username and password and not just the first line?

Upvotes: 3

Views: 210

Answers (3)

pylang
pylang

Reputation: 44485

I'd recommend outputting a json file instead of a text file and look up data as a dictionary. However, since you write lines that look like lists, you can evaluate the string as if it were an actual list with ast.literal_eval().

Given

A file Database.txt

['James', 'Jul17', '1234', '[email protected]', 'TP1234', 'password']
['Jon', 'Sep17', '5567', '[email protected]', 'TP2345', 'passwords']
['Han', 'Oct17', '7554', '[email protected]', 'TP5546', 'passwords1']
['Klye', 'Oct17', '2234', '[email protected]', 'TP0094', 'passwords2']

created from this refactored function:

def signup():
    """User sign up."""
    name  = str(input("Name: "))
    intake = (str(input("Intake: ")))
    hp = str(input("Phone Number: "))
    email = str(input("E-mail: "))
    tp = str(input("Student ID: "))
    pw = str(input("Password: "))
    occupants_data = [name, intake, hp, email, tp, pw]

    # Safely open/close files
    with open("Database.txt", "a") as f:
        f.write(str(occupants_data) + "\n")

Code

from ast import literal_eval


def login(): 
    """User sign in."""
    tp = str(input("Please input TP Number: "))
    password = str(input("Please input password: "))

    with open("Database.txt", "r") as f:
        for line in f.readlines():
            if not line or line =="\n":
                continue

            user_data = literal_eval(line)         # convert string-list to a list
            if tp == user_data[-2]:
                if password == user_data[-1]:
                    print("Welcome")
                    return
                else:
                    print ("Username or Password doesn't match")
                    return
        print("Error")

Demo

enter image description here


Details

The signup() function was refactored by:

  • lowercase function name according to PEP8
  • extra parentheses removed
  • the with statement was used to safely open and close files

This can be used to generate the Database.txt file.

The login() function was refactored by:

  • lowercase function and variable names
  • converting the password input to a string
  • using a with statement to handle the file
  • iterating each line of the file, ignoring blank lines and newlines
  • list-like lines are converted to lists
  • rather than search lists, data is more quickly pulled from fixed indices
  • the loop short-circuits if an input is successful, otherwise an error is printed

The next concept you might consider is exception handling raising errors instead of printing them and handling user KeyboardInterupt to quit a prompt.

Upvotes: 1

neehari
neehari

Reputation: 2612

input() returns a string, so no need for explicit conversion with str(). Better use with statement when dealing with file objects as it closes them automatically.

Defining signUp():

def signUp(): #USER SIGN UP    
    name = input("Name: ")
    intake = input("Intake: ")
    hp = input("Phone Number: ")
    email = input("E-mail: ")
    tp = input("Student ID: ")
    pw = input("Password: ")

    OccupantsData = [name, intake, hp, email, tp, pw]

    with open("Database.txt", "a") as db:
        db.write(' '.join(OccupantsData)) # Writing it as a string

Calling signUp():

signUp()

Name: x
Intake: something
Phone Number: 123-456-7890
E-mail: [email protected]
Student ID: x123
Password: password
>>> 

Defining logIn():

def logIn(): #USER SIGN IN
    TP = input("Please input TP Number: ")
    password = input("Please input password: ")

    with open("Database.txt") as db:
        for line in db:
            line = line.split(' ') # Making it a list

            if TP in line:
                if password in line:
                    print("Welcome")
                else:
                    print ("Username or Password doesn't match")
                    logIn()
            else:
                print("Error")
                logIn()

Calling logIn():

logIn()

Please input TP Number: x123
Please input password: pass
Username or Password doesn't match
Please input TP Number: x123
Please input password: password
Welcome
>>> 

Python Tutorial says:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.

Upvotes: 0

ndrwnaguib
ndrwnaguib

Reputation: 6115

In order to match the input with one or more of the txt file content, you need to loop over it. Moreover, to check if password is in the list you have to cast it into string . So your login code would become:

def logIn():  # USER SIGN IN
TP = str(input("Please input TP Number:"))
password = str(input("Please input password:"))
f = open("Database.txt", "r")
for line in f.readlines():
    if (TP) in line:
        if password in line:
            print("Welcome")
        else:
            print ("Username or Password doesn't match")
            logIn()
    else:
        print("Error")

Good Luck!

Upvotes: 0

Related Questions