使用 Python 3 读取并递增文件中的计数器

Read and increment counter in file using Python 3

我正在使用 Flask 编写 pastebin 服务。对于每个请求,我需要将数据存储在 /data/1191 中并更新 counter.txt 以现在包含 1192,而不是 1191.

我能做得更好吗:

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

(请注意我已经根据评论修改了代码)

这可能是一个开始:

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