Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading