When you want to open a file, you should almost always use the with
statement:
with open('User_Details.txt') as read_file:
# Do reading etc. with `read_file` variable
This will ensure that any errors are being handled correctly and the file is not left open.
Now that the file is open, we need to loop through each line until we find one that matches our username. I hope you know how for
loop works:
username = 'Username: 13' # Get this however you want
with open('User_Details.txt') as read_file:
for line in read_file:
line = line.strip() # Removes any unnecessary whitespace characters
if line == username:
# We found the user! Next line is password
And we need to get the next line which contains the password. There are many ways to get the next line, but one simple way is to use the next()
function which simply gets us the next element from an iterable (the next line from a file in this case):
username = 'Username: 13'
with open('User_Details.txt') as read_file:
for line in read_file:
line = line.strip()
if line == username:
password = next(read_file)
break # Ends the for loop, no need to go through more lines
Now you have a password and an username, and you can do whatever you want with them. It's often a good idea to have the inputs and outputs outside of your program's logic, so don't print the password right inside the for
loop, but instead just receive it there and then do the printing outside.
You might even wanna turn the whole search logic into a function:
def find_next_line(file_handle, line):
"""Finds the next line from a file."""
for l in file_handle:
l = l.strip()
if l == line:
return next(file_handle)
def main():
username = input("Please enter the username you wish to see the password for: ")
username = 'Username: ' + username
with open('User_Details.txt') as read_file:
password = find_next_line(read_file, username)
password = password[len('Password: '):]
print("Password '{0}' found for username '{1}'".format(password, username))
if __name__ == '__main__':
main()
Finally, it's absolutely insane to store anything in this format (not to mention password security stuff, but I get you're just learning stuff), why not do something like:
username:password
markus:MarkusIsHappy123
BOB:BOB'S PASSWORD
This could then easily be converted into a dict:
with open('User_Details.txt') as read_file:
user_details = dict(line.strip().split(':') for line in read_file)
And now to get a password for an username, you'd do:
username = input('Username: ')
if username in user_details:
print('Password:', user_details[username])
else:
print('Unknown user')