Python3 - 如何使用变量将数字写入文件并将其与文件中的当前数字相加

Python3 - How to write a number to a file using a variable and sum it with the current number in the file

假设我有一个名为 test.txt 的文件,目前它里面有数字 6。我想使用诸如 x=4 之类的变量,然后写入文件并将两个数字相加并将结果保存在文件中。

    var1 = 4.0
    f=open(test.txt)
    balancedata = f.read()
    newbalance = float(balancedata) + float(var1)
    f.write(newbalance)
    print(newbalance)
    f.close()

它可能比您尝试制作的要简单:

variable = 4.0

with open('test.txt') as input_handle:
    balance = float(input_handle.read()) + variable

with open('test.txt', 'w') as output_handle:
    print(balance, file=output_handle)

确保 'test.txt' 在您 运行 此代码之前存在并且其中有一个数字,例如0.0 -- 如果文件不存在,您还可以修改代码以首先处理创建文件的问题。

文件只读和写字符串(或 bytes 以二进制模式打开的文件)。您需要先将浮点数转换为字符串,然后才能将其写入文件。

可能 str(newbalance) 是您想要的,但您可以根据需要使用 format 自定义它的显示方式。例如,您可以使用 format(newbalance, '.2f').

将数字四舍五入到小数点后两位

另请注意,您不能写入仅为读取而打开的文件,因此您可能需要使用模式 'r+'(允许读取和写入)结合 f.seek(0)调用(如果新数字字符串的长度可能比旧长度短,则可能 f.truncate()),或者关闭文件并以 'w' 模式重新打开它(这将为您截断文件)。