Martin
Martin

Reputation: 75

How to increase a number in a text file by one and write it back to the file?

I am trying to read a number from a txt file. then increase it by 1 then write that number to the file but it just empties the file.

How do I fix this?

Code:

f = open('BestillingNr.txt', 'r')
bestillingNr = int(f.read())
bestillingNr += 1

f2 = open('BestillingNr.txt', 'w')
f2.write(f'{str(bestillingNr)}')

f.close()
f2.close

Upvotes: 0

Views: 511

Answers (2)

mtdot
mtdot

Reputation: 312

after this line f2.write(f'{str(bestillingNr)}'), you should add flush command f2.flush()

This code is work well:

f = open('BestillingNr.txt', 'r')
bestillingNr = int(f.read())
f.close()
bestillingNr += 1

f2 = open('BestillingNr.txt', 'w')
f2.write(f'{str(bestillingNr)}')
f2.flush()
f2.close()

Upvotes: 0

scotty3785
scotty3785

Reputation: 7006

You need to close the second file. You were missing the () at the end of f2.close so the close method actually won't have been executed.

In the example below, I am using with which creates a context manager to automatically close the file.

with open('BestillingNr.txt', 'r') as f:
    bestillingNr = int(f.read())

bestillingNr += 1

with open('BestillingNr.txt', 'w') as f2:    
    f2.write(f'{str(bestillingNr)}')

Upvotes: 2

Related Questions