繁体   English   中英

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))

它已成功从文件中读取值,但是在写入时,文件中未存储任何内容。 这是怎么了

更新

我要替换旧值,而不是附加到旧值。 删除旧值,然后放新值。

我不知道您使用的是哪个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))

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

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))

以下内容可以为您提供帮助: 入门Python:读取和写入同一文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM