How to delete replace string in text file from python?

So I have a script that I want to have save the amount of hours you have logged. The data is kept in a .txt file and the data is the only thing in that file. There will always only be one line in the file. I want to read the current number saved in the file, delete the number, then replace it with a new number that I get from the user.

with open("fullHours.txt", "r+") as fullHours:
    fullHours.write(str(int( + int(new_number)))

This code just appends to the current integer, but I want the original number in the file to be replaced with the new number.

>Solution :

First open the file in "r" mode, read the current data, and close the file.

Then open the file in mode "w", and write the new value.

Leave a Reply