使用Python 3在文件中读取和增加计数器

时间:2015-07-24 11:43:40

标签: file python-3.x counter

我正在使用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) )

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

1 个答案:

答案 0 :(得分:1)

这可能是一个开始:

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