我正在使用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) )
(请注意我已根据评论修改了代码)
答案 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) )