【问题标题】:python read value from file and change it and write back to filepython从文件中读取值并更改它并写回文件
【发布时间】:2017-04-27 10:47:35
【问题描述】:

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

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 readfile writefile


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-26
      • 2017-11-24
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2019-03-11
      • 2021-02-16
      相关资源
      最近更新 更多