Search code examples
pythonreadfilewritefile

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


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.


Solution

  • 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