我有文字" podaci.txt"像这样的文件:
Name|Lastname|1-000-1|1234|5000
Name1|Lastname1|1-000-1|4321|15500
其中1234
和4321
是密码。
这样的代码:
def ProveraStanja(self):
file_data = open("podaci.txt").readlines()
for i in file_data:
i=i.strip("\n").split("|")
account_balance=i[4]
self.top = Toplevel()
self.la = Label(self.top,text="Acaunt balance: ")
self.la.grid()
self.Results = Label(self.top, text = account_balance)
self.Results.grid()
self.bt = Button(self.top,text='Potvrdi', command = self.potvrdiBtn)
self.bt.grid()
self.top.resizable(0,0)
如何显示登录用户的帐户余额?
我的问题是python总是只显示最后一个用户的accaunt余额。
例如,如果我以1234
身份登录,它仍会显示15500
作为我的帐户
答案 0 :(得分:0)
您遍历文件的所有行,但始终覆盖account_balance。
将您的account_balance创建为字典,如:
account_balance = {}
并在for循环中将余额存储在正确的字段中。
account_balance[i[3]] = i[4]
使用密钥
访问该值account_balance[1234]
答案 1 :(得分:0)
您的代码存在的问题是您没有保留每行的数据。相反,您在for循环的每次迭代时都会覆盖account_balance
。因此,只保留最后一个值,该值对应于文件中的最后一行。
你可以这样做:
def getBalance(myPin):
with open("podaci.txt", "r") as file:
for line in file.readlines():
split_line = line.strip().split("|")
if split_line[3] == myPin:
return split_line[4]
return 0 #Return 0 balance if the PIN does not exist
我们在这里做的是:
with
语句打开文件,您可以阅读该语句
here。'|'
字符作为分隔符拆分每一行。检查列表中的第4项(索引3)是否与myPin
相同。
当然,这种解决方案远非理想。我让它尽可能简单,以便易于理解。有很多方法可以改进它。例如,您应该添加某种形式的冗余。
def getBalance(myPin):
with open("podaci.txt", "r") as file:
for line in file.readlines():
split_line = line.strip().split("|")
if len(split_line) == 5: #Make sure that the line is valid
if split_line[3] == myPin:
return split_line[4]
return 0 #Return 0 balance if the PIN does not exist
我在这里做的是添加了一个额外的if
语句,以确保该行具有有效条目所需的项目数。这样,读取空或无效的行不会导致异常。
然而,绝对最佳的解决方案(除了使用适当的数据库)是使用class来保存我们的输入数据:
class Account:
def __init__(self, list):
self.Name = list[0]
self.LastName = list[1]
self.AccountNumber = list[2]
self.Pin = list[3]
self.Balance = list[4]
accounts = [] #Accounts are all kept here
#Load all accounts from the file
def getAccounts():
with open("podaci.txt", "r") as file:
for line in file.readlines():
split_line = line.strip().split("|")
if len(split_line) == 5: #Make sure that the line is valid
accounts.append(Account(split_line))
#Find the account that matches the inputted PIN
def findBalance(myPin):
for account in accounts:
if account.Pin == myPin:
return account.Balance
这样,我们的数据更有条理,添加功能更加简单。对于最后一个例子,我还修改了代码来读取文件并只加载一次帐户,如果不使用类就很难做到。
只是为了好玩,您可以通过将所有字符串处理移动到实际类来更进一步:
class Account:
def __init__(self, name, lastName, accountNumber, pin, balance):
self.Name = name
self.LastName = lastName
self.AccountNumber = accountNumber
self.Pin = pin
self.Balance = balance
def Decode(line):
split_line = line.strip().split("|")
if len(split_line) == 5: #Make sure that the line is valid
return Account(split_line[0], split_line[1], split_line[2], split_line[3], split_line[4])
accounts = []
def getAccounts():
with open("podaci.txt", "r") as file:
for line in file.readlines():
accounts.append(Account.Decode(line))