簡體   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