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

前端 未结 2 1767
暗喜
暗喜 2021-01-25 14:36

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\') a         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-25 14:57

    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

提交回复
热议问题