【问题标题】:Creating an object from a list of attributes in a file, Python从文件中的属性列表创建对象,Python
【发布时间】:2022-01-17 21:09:39
【问题描述】:

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

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

2,IE30983,joe,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)```

【问题讨论】:

  • 你为什么要遍历split_line
  • split_line[6] == 's' 是关于什么的?这不适用于显示的文件布局(只有 6 列,其中任何一个都没有“s”)
  • @Stuart 这是我的错误,每行最后都应该包含一个字符,现在将编辑

标签: python file class object oop


【解决方案1】:

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

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)

【讨论】:

  • 这帮助我让它工作谢谢
猜你喜欢
  • 2014-10-17
  • 2020-11-22
  • 2019-12-13
  • 1970-01-01
  • 2011-02-13
  • 2014-03-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多