我有一個全行的檔案,其中每一行都有一個銀行帳戶物件的屬性。檔案布局示例:
1,IE33483,alex,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)```
uj5u.com熱心網友回復:
你可以做這樣的事情 - 不需要遍歷每一行中的部分。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380692.html
