# get current filenum, or 1 to start
try:
with open('counterfile', 'r') as f:
filenum = int(f.read())
except (IOError, ValueError):
filenum = 1
# write next filenum for next run
with open('counterfile', 'w') as f:
f.write(str(filenum + 1))
filename = 'file%s.txt' % filenum
with open(filename, 'w') as f:
f.write('whatever you need\n')
# insert all processing here, write to f
In Python 2.5, you also need a first line of from __future__ import with_statement
to use this code example; in Python 2.6 or better, you don't (and you could also use a more elegant formatting solution than that %
operator, but that's a very minor issue).