CrustyPablo
CrustyPablo

Reputation: 45

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(fullHours.read()) + 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.

Upvotes: 1

Views: 239

Answers (2)

nigh_anxiety
nigh_anxiety

Reputation: 2337

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.

Upvotes: 2

Blackgaurd
Blackgaurd

Reputation: 658

Move the cursor to the start of the file to remove the old content.

with open("fullHours.txt", "r+") as fullHours:
    previous_number = fullHours.read()
    fullHours.seek(0)
    fullHours.write(str(int(previous_number) + int(new_number)))

Upvotes: 0

Related Questions