justin medina
justin medina

Reputation: 11

overwriting a text file in python

I am currently writing a code to keep track of, add to, and reset an arbitrary unit of time for my campaign, the problem I am having is the number keeps adding on to what is already written. so if i were to start at 5, and try to reset it to 0, it would change to 50 instead, appending instead of overwriting. How is it that I would fix this, or is there more steps I need to make this work?

my reset program is as follows:

time=open('timefile.txt','r+')
time.write("0")
time.close()

Upvotes: 1

Views: 39

Answers (2)

user5154816
user5154816

Reputation:

With following code, you don't need to close the file:

with open('timefile.txt', 'w') as f:
    f.write("0")

Upvotes: 2

jacoblaw
jacoblaw

Reputation: 1283

time=open('timefile.txt','w')
time.write("0")
time.close()

You are currently opening it for read-write, with the file pointer at the beginning of the text. Open it only for writting to overwrite the contents.

Upvotes: 1

Related Questions