繁体   English   中英

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

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

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

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

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

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

我试图创建一些代码来搜索此文件以查找用户输入(例如,他们输入他们的 id,这是每行的第一个元素),并将使用这所有 3 个属性来创建 object。 有什么帮助吗? 这是我迄今为止尝试过的,但它似乎不适用于包含多行的文件:

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 模块

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)

暂无
暂无

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

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