简体   繁体   中英

Python: How do you read a specific line from a text file based on the previous line?

I apologize if this is a duplicate, but I couldn't find anything that matched my specific question. I am creating a project that acts like a bank system and reads username, password, and amount from a text file. I have a text file set up with username on first line, password on second line, and amount on third and then another block that has same pattern. I am checking if the username that the user inputs is in the file, then checks the next line and checks if the password enters is the next line.

f = open_file("D:/PythonProjects/banking.txt", "r") #open file   
read_file = f.read() #store contents of file in variable
name = input("Username: ")
pword = input("Password: ")
if name in read_file: #check if username is in file contents variable
    if pword in read_file:
       print("match")

So far, this prints 'match' if you enter name/password in the file, but I'm only looking for the matching password. I also have a function that returns the next line and tried to call that twice in order to get the line after the name line.

def next_line(the_file):
'''Returns the next line from the_file'''
line = the_file.readline()
line = line.rstrip()
return line

Security (encryption) and efficiency (database) issues mentioned in the other answers aside, here is a possible solution parsing your file directly into a dictionary:

data = {}
filename = "D:/PythonProjects/banking.txt"
with open(filename, "r") as fh:
    username = ""
    password = ""
    amount = -1

    line_mode = 1
    for line in fh:
        if line_mode % 3 == 1:
            username = line.strip()
            data[username] = {}
        elif line_mode % 3 == 2:
            password = line.strip()
            data[username][password] = -1
        elif line_mode % 3 == 0:
            amount = float(line.strip())
            data[username][password] = amount

        line_mode += 1 

input_name = input("Username: ")
input_password = input("Password: ")

if input_name in data and input_password in data[input_name]:
    print("amount", data[input_name][input_password])
else:
    print("User not found or password incorrect")

EDIT: A shorter solution came into my mind:

filename = "D:/PythonProjects/banking.tx"
data = {}

with open(filename, "r") as fh:
    lines = [line.strip() for line in fh.readlines()]
    for i in range(0, len(lines), 3):
        data.setdefault(lines[i], {})[lines[i+1]] = lines[i+2]

lines[i] , lines[i+1] , lines[i+3] are the username, password and amount.

dict.setdefault(key, default) either returns the value in data for the key lines[i] , ie the entry for a username, if it is already present, or creates a new dict with the username as key and returns it afterwards. It is now ensured that data[lines[i]] exists and can be filled with the password ( lines[i+1] ) and amount ( lines[i+2] ).

Better use a database. SQLite is good starting point. You don't even have to install anything (since SQLite is already included with Python). Have fun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM