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

纵然是瞬间 提交于 2020-01-30 08:15:21

问题


i am reading a value from a file and then adding up with another and then writing back to the same 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))

it is successfully reading the value from file, but when writing, nothing is stored in the file. what is wrong here?

update

I want to replace the old value, not append to it. Erase the old value and then put the new value instead.


回答1:


you can't open your file twice simultaneously, your code should look like this:

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

A look at this could help you: Beginner Python: Reading and writing to the same file




回答2:


I do not know which Python version you use, but both 2.7.13 and 3.6.1 versions give me the following error: b'' is not a number!. So because an error is raised, the write instruction is not interpreted.

The with statement is evaluated from left to right. So first, your file is open in read mode. Right after that, it is open in write mode and that causes the file to be truncated: there is nothing more to read.

You should proceed in two steps:

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


来源:https://stackoverflow.com/questions/43655585/python-read-value-from-file-and-change-it-and-write-back-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!