我一直在开发银行应用程序。我创建了登录/注册系统,其中每个用户都显示为 txt 文件。每个txt文件包含4行:登录名、密码、安全码等是存款或取款后的余额。我正在努力如何创建第四行。在我现有的代码中,给定的存款写在现有值旁边。是否可以读取用 txt 编写的字符串行,以便我可以将其添加到给定的存款余额中,然后显示一个值?第 4 行的默认值也是 0,它是一个字符串。
self.balance = int(self.balance) + self.amt
file=open(self.name, "a+") # <----- Creates line in user's file.
file.write(int(self.balance))
messagebox.showinfo("balance","You have deposit: "+str(self.balance))
file=open(self.username_info, "w") <------ All user s are created as txt file
file.write(self.username_info+"\n")
file.write(self.password_info+"\n")
file.write(self.code_info+"\n")
file.write(self.cash)
balance = file.readlines()[3]
如果文件以“r”模式打开,您可以像这样读取余额存款,然后对该变量执行您喜欢的任何操作,然后重写四行。
以“写入模式”打开文件可确保不附加任何数据。一切都只是被覆盖而不是被修改,但因为你只有 4 行,所以没关系。
# Open the file, read its content, close the file.
file = open(file_name, "r")
lines = file.readlines()
file.close()
# Get the interesting info from the stored lines.
login = lines[0].rstrip() # <- add .rstrip() here if you want to get rid of the spaces and line feeds.
password = lines[1].rstrip()
security_code = lines[2].rstrip()
balance = int(lines[3]) # <- notice the int() for conversion.
# Do something on the balance, for example:
balance += deposit
# Open the file and write back the 4 lines, with the 4th modified.
file = open(file_name, "w")
file.write(login + "\n")
file.write(password + "\n")
file.write(security_code + "\n")
file.write(str(balance) + "\n")
file.close()
如果您有兴趣,这里有一个更紧凑的版本:
# Open the file, read its content, close the file.
with open(file_name, "r") as file:
lines = file.readlines()
# Open the file and write back the 4 lines, with the 4th modified.
with open(file_name, "w") as file:
file.write(lines[0])
file.write(lines[1])
file.write(lines[2])
file.write("%d \n" %(int(lines[3])+deposit))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句