python - 文本文件中的整数值未更改

标签 python

我有一个函数可以检索文本文件中内容的当前值,然后在程序结束时将值增加 1。但是,该值并不总是增加。可能是什么原因?

获取var值

def get_var_value(filename="varstore.dat"):
    with open(filename, "r+") as f:
        val = int(f.read() or 0)
        f.seek(0)
        f.truncate()
        return val

将值增加 1:

def increase_var_value(filename="varstore.dat"):
    with open(filename, "r+") as f:
        val = int(f.read() or 0) +1
        f.seek(0)
        f.truncate()
        f.write(str(val))
        return val

最佳答案

get_var_value函数不需要查找和截断文件。它会在 increment_var_value 读取文件之前删除该文件的内容。因此,increment_var_value 始终将其读取为 0,然后将其递增 1,因此该值始终为 1。

代码现在是,

def get_var_value(filename="varstore.dat"):
    with open(filename, "r") as f:
        val = int(f.read() or 0)
        return val


def increase_var_value(filename="varstore.dat"):
    with open(filename, "r+") as f:
        val = int(f.read() or 0) + 1
        f.seek(0)
        f.truncate()
        f.write(str(val))
        return val

关于python - 文本文件中的整数值未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54312487/

相关文章:

python - 具有冗余约束的不可行解 - PuLP 和 COIN-OR

php - PHP 中 crc32b 的输出不等于 Python

python - Pyramid unicorn 和女服务员

python - 如何使用 python boto3 向本地 SQS 队列发送消息?

python - 我是否应该在使用 numpy.array 时使用 numpy.float64 而不是 Python float

python - 如何删除数据类属性

python - django 的 makemigrations 中的自动回答

python - "any value"的 PySpark 聚合函数

Python 网络服务

Python,模拟 : raise exception