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

ledinos1

我一直在开发银行应用程序。我创建了登录/注册系统,其中每个用户都显示为 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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何将str转换为int?

来自分类Dev

如何将str转换为int

来自分类Dev

将字典中的 str 项转换为 int 并将 datetime.datetime 变量转换为 int

来自分类Dev

将int向量转换为str向量

来自分类Dev

将int转换为str用于循环

来自分类Dev

Python,如果转换为str / int

来自分类Dev

将列表的元素从 str 转换为 int

来自分类Dev

如何将用户的字符串输入(例如“ int”或“ float”)转换为str和float类型?

来自分类Dev

如何将从文件中读取的数字从 str 转换为 int?

来自分类Dev

将Str(十六进制int)转换为Dec Int

来自分类Dev

如何使用json.dumps()将所有int转换为嵌套字典中的str?

来自分类Dev

如何在python中将字符串转换为int?

来自分类Dev

如何在bash中将字符串转换为int?

来自分类Dev

如何在python中将字符串转换为int?

来自分类Dev

如何在inloop中将int转换为字符串

来自分类Dev

如何在python中将字符串转换为int?

来自分类Dev

如何在bash中将字符串转换为int?

来自分类Dev

如何在C ++中将字符串转换为int?

来自分类Dev

如何在wpf中将int转换为字符串?

来自分类Dev

将str转换为int的简单方法?C ++

来自分类Dev

将Str列表转换为Int列表(Python)

来自分类Dev

TypeError:无法将int隐式转换为str

来自分类Dev

在Python中将列表[str]转换为列表[int]

来自分类Dev

将带单双引号的str转换为int

来自分类Dev

解析字符串并将某些元素转换为int

来自分类Dev

解析并将字符串转换为int rails

来自分类Dev

字符串转换为int太大

来自分类Dev

字符串转换为int太大

来自分类Dev

将 int[][] 转换为字符串