python 从文件中读取值并更改它并写回文件

python read value from file and change it and write back to file

我正在从一个文件中读取一个值,然后与另一个值相加,然后写回同一个文件。

total = 0
initial = 10
with open('file.txt', 'rb') as inp, open('file.txt', 'wb') as outp:
    content = inp.read()
    try:
        total = int(content) + int(initial)
        outp.write(str(total))
    except ValueError:
        print('{} is not a number!'.format(content))

它正在成功地从文件中读取值,但是在写入时,文件中没有存储任何内容。 这里有什么问题?

更新

我想替换旧值,而不是附加到它。擦除旧值,然后用新值代替。

您不能同时打开您的文件两次, 您的代码应如下所示:

total = 0
initial = 10

with open('file.txt', 'rb') as inp:
    content = inp.read()
    total = int(content) + int(initial)

with open('file.txt', 'wb') as outp:
    outp.write(str(total))

看看这个可以帮助你: Beginner Python: Reading and writing to the same file

我不知道你用的是哪个Python版本,但是2.7.13和3.6.1版本都给我以下错误:b'' is not a number!。因此,因为引发了错误,所以不解释写入指令。

with 语句从左到右求值。所以首先,您的文件以读取模式打开。紧接着,它以写入模式打开,导致文件被截断:没有更多内容可读。

您应该分两步进行:

total = 0
initial = 10

# First, read the file and try to convert its content to an integer
with open('file.txt', 'r') as inp:
    content = inp.read()

    try:
        total = int(content) + int(initial)
    except ValueError:
        print('Cannot convert {} to an int'.format(content))


with open('file.txt', 'w') as outp:
    outp.write(str(total))