从文件中的属性列表创建对象,Python

Creating an object from a list of attributes in a file, Python

我有一个充满行的文件,其中每一行都有一个银行帐户对象的属性。文件布局示例:

1,IE33483,亚历克斯,1,100,20,s

2,IE30983,乔,1,0,20,c

3,IE67983,tom,1,70,20,s

我正在尝试创建一些代码来搜索此文件以获取用户输入(例如,他们输入他们的 ID,这是每行的第一个元素),并将使用这所有 3 个属性来创建一个对象。有什么帮助吗?到目前为止,这是我尝试过的方法,但它似乎不适用于包含多行的文件:

accid=input("Enter ID of account to manage:\n")
        f = open("accounts.txt", "r")
        for line_str in f:
            split_line = line_str.split(",")
            accid2 = split_line[0].strip()
        if split_line[6] == 's':
              for line in split_line:
                if accid2 == accid:
                  current_acc=SavingsAccount(accid, split_line[1],
                          split_line[2],
                          split_line[3],
                          split_line[4],
                          split_line[5],
                          split_line[6])
                  print("Logged in as: ")
                  print(current_acc.accid)```

您可以这样做 - 无需遍历每一行中的部分。

def get_account_by_id(id, type_)
    with open("accounts.txt") as f:
        for line in f:
            parts = line.split(",")
            if parts[0] == id and parts[6] == type_:
                return SavingsAccount(*parts)

accid = input("Enter ID of account to manage:\n")
account = get_account_by_id(accid, type_="s")
if account is not None:
    print(f"Logged in as {account.accid}")

或者更好的是,如果您的文件是有效的 CSV 文件,请使用 CSV module

import csv

def get_account_by_id(id, type_)
    with open("accounts.txt") as f:
        for row in csv.reader(f):
            if row[0] == id and row[6] == type_:
                return SavingsAccount(*row)