简体   繁体   English

Python:您如何基于前一行从文本文件中读取特定行?

[英]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. lines[i]lines[i+1]lines[i+3]是用户名,密码和数量。

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. dict.setdefault(key, default)或者返回键lines[i]数据值,即用户名的条目(如果已经存在),或者创建一个以用户名作为键的新dict并随后返回。 It is now ensured that data[lines[i]] exists and can be filled with the password ( lines[i+1] ) and amount ( lines[i+2] ). 现在确保data [lines [i]]存在并且可以用密码( lines[i+1] )和数量( lines[i+2] )填充。

Better use a database. 更好地使用数据库。 SQLite is good starting point. SQLite是一个很好的起点。 You don't even have to install anything (since SQLite is already included with Python). 您甚至无需安装任何程序(因为Python已包含SQLite)。 Have fun. 玩得开心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中的特定行中访问文本文件中的数据? - How do you access data in a text file in a specific line in Python? 我如何只读取 .text 文件的特定行? Python - How do i read only a specific line of a .text file? Python 使用python从文件中的特定行读取前几行 - read previous lines from specific line in a file using python 如何从 python 中的文本文件中删除特定行 - How do I remove a specific line from a text file in python PYTHON Re:性能:从文本文件中的特定行开始,读取一行并根据制表符对其进行拆分,然后访问每个元素。 - PYTHON Re: Performance: Starting from a specific line in a text file read a line and split it based on tabs, then access each element. 你如何将一个文本文件读入字典,其中一行的信息由'\t'分隔 python - How do you read a text file into a dictionary with the information on one line separated by '\t' python 如何读取数据对应于python中60GB文本文件中的特定行号? - How to read data corresponds to specific line numbers from a 60GB text file in python? 如何从 Python 中的文本文件的特定行中提取文本? - How to extract text from a specific line of a text file in Python? 如何逐行读取.txt文件并使用它登录大量帐户(Python,Selenium) - How do you read a .txt file line by line and use it to Login into tons of Accounts (Python, Selenium) 如何从文本文件中打印行的特定部分? - How do I print a specific section of a line from a text file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM