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

时间:2019-03-25 11:55:33

标签: python

我一直在开发银行应用程序。我创建了登录/注册系统,其中每个用户都显示为txt文件。每个txt文件包含4行:登录名,密码,安全码,等等。我正在努力创建第四行。在我现有的代码中,给定的存款写在exisitng值旁边。是否可以读取以txt格式编写的字符串行,以便将其添加到给定的存款余额中,然后显示一个值?另外,第四行的默认值为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)

2 个答案:

答案 0 :(得分:1)

with open("info","r") as fd:
    username,password,code,cash= [i.strip() for i in fd if len(i.strip())>1]

答案 1 :(得分:0)

如果文件以“ r”模式打开,则您可以像这样balance = file.readlines()[3]读取余额存款,然后使用此变量执行所需的任何操作,然后重写四行。

以“写模式”打开文件可确保不附加任何数据。一切都被覆盖而不是修改,但是由于只有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))