Python 如何在读取str并将其转换为int之前清除字符串

Python 如何在读取str并将其转换为int之前清除字符串,python,Python,我一直在开发银行应用程序。我已经创建了登录/注册系统,其中每个用户都显示为一个txt文件。每个txt文件包含4行:登录、密码、安全代码等,是存款或取款后的余额。我正在绞尽脑汁想如何创建第四行。在我现有的代码中,给定的存款写在现有值的旁边。是否可以读取用txt写的字符串行,以便我可以将其添加到给定的deposoit余额中,然后显示一个值?第四行的默认值也是0,它是一个字符串 self.balance = int(self.balance) + self.amt fi

我一直在开发银行应用程序。我已经创建了登录/注册系统,其中每个用户都显示为一个txt文件。每个txt文件包含4行:登录、密码、安全代码等,是存款或取款后的余额。我正在绞尽脑汁想如何创建第四行。在我现有的代码中,给定的存款写在现有值的旁边。是否可以读取用txt写的字符串行,以便我可以将其添加到给定的deposoit余额中,然后显示一个值?第四行的默认值也是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)
self.balance=int(self.balance)+self.amt

file=open(self.name,“a+”)#您可以像这样读取余额存款
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()

想再解释一点吗?如果在代码中包含解释,这个答案会更好。例如,对于刚开始编程的人来说,他们不知道这是额外的代码,还是替换了原始代码的一行或多行的代码。所以test=file.readlines()[3],然后test.write(str(self.balance))?也可以将写入的字符串读取为int,这样我就可以通过数学方式将两个值相加得到一个值?不,您不能执行
test。写入
,因为
test
是存储第四行结果的变量!您的意思是
file.write
?如果要将字符串转换为int,只需调用
int()
。例如
number=int(string\u to\u convert)
。根据您的代码再次输入一个。余额是第四行的存储,所以要更改它,我必须再次打开文件,但“w”,然后写入新内容?完全正确。我编辑后给出了一个完整的例子,希望能有所帮助。好吧,我已经计算出如何将余额+存款作为一个值,但是新的值是相邻写的
# 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))
with open("info","r") as fd:
    username,password,code,cash= [i.strip() for i in fd if len(i.strip())>1]