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

Time:12-15

I have a file full of lines, where each line has attributes for a bank account object. Example of file layout:

1,IE33483,alex,1,100,20,s

2,IE30983,joe,1,0,20,c

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

Im trying to create some code that will search this file for user input (e.g they enter their id which is the first element of each line), and will use these all 3 attributes to create an object. Any help? This is what I have tried so far, but it doesn't seem to work for a file with more than one line:

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)```

CodePudding user response:

You can do something like this - no need to iterate through the parts within each line.

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}")

Or better, if your file is a valid CSV file, use the 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)
  • Related