Home > Software engineering >  How to seperate multiple words from a example.txt file to seperate variables in python
How to seperate multiple words from a example.txt file to seperate variables in python

Time:01-25

I am trying to code a login verificater where the username and passwords are stored into a separate text file, I am trying to get the text file to load up on Python and each separate word to be loaded onto separate variables.

For example, given the following text file:

admin, 1234
bigadmin, 5678

where admin is the username and 1234 is the password, I want the same details loaded up onto Python but split up into two separate variables:

username = "admin"
password = "1234"

Here's the solution I'm currently using:

tempuserdatabase = open('user.txt')
userdatabase = tempuserdatabase.read().split(",")

username = input("Please enter your username:")
password = input("Please enter your password:")

if username == userdatabase[0] and password == userdatabase[1]:
    print("successful")
else:
    print("Please try again")

This was the initial code however this method has not been working. So while coding the rest of the code I figured out that is more convenient for the code to just be separated and stored into two different variables so that I can use it later on as well minimizing the amount of lines.

CodePudding user response:

If you print (userdatabase[1]) it says that your password should be

' 1234'

but if you use .strip()...

if username == (userdatabase[0]) and password == (userdatabase[1]).strip(): print("successful") else: print("Please try again")

it works using '1234' as your password

CodePudding user response:

You could try using one line for each username and their password. Within a line you can use a space to separate the username and password... Then just have to read the file line by line. For each line, separate the login name from the password using the split() method. After that you can load all user information in a dictionary... for example... I hope I helped you :-)

tempuserdatabase = open('user.txt')

# Loading dictionari
userDictionary = {}
for userLine in tempuserdatabase:
    userName = userLine.split()[0]
    userPassword = userLine.split()[1]
    userDictionary[userName] = userPassword

print(userDictionary)

# Checking user
username = input("Please enter your username:")
password = input("Please enter your password:")

if username in userDictionary:
    if userDictionary[username]  == password:
        print("successful")
    else:
        print("Please try again")
else:
    print("Please try again")

File content:

admin 1234
bigadmin 5678
  • Related