P i
P i

Reputation: 30684

Read and increment counter in file using Python 3

I am writing a pastebin service using Flask. For each request, I need to stash the data in say /data/1191 and update counter.txt to now contain 1192, not 1191.

Can I do any better than:

import os

try:
    with open( 'counter.txt', 'r' ) as f:
        counter = int( f.readline() ) + 1
    os.remove( 'counter.txt' ) 
except:
    counter = 0

req_data = str(counter)

filename = 'data/' + str(counter)
os.makedirs(os.path.dirname(filename), exist_ok=True) 

with open(filename, "w") as f:
    f.write(req_data)

with open( 'counter.txt', 'w' ) as f:
    f.write( str(counter) )

(please note I have revised the code in light of the comments)

Upvotes: 0

Views: 4148

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46849

this may be a start:

req_data = 'someting'

try:
    with open( 'counter.txt', 'r' ) as fle:
        counter = int( fle.readline() ) + 1
except FileNotFoundError:
    counter = 0

with open( 'data/{}'.format(counter), 'w' ) as fle:
    fle.write( req_data )

with open( 'counter.txt', 'w' ) as fle:
    fle.write( str(counter) )

Upvotes: 3

Related Questions