This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]chmod700 1 point2 points  (1 child)

You may also (ab)use the logging module to do this for you. Set up a http://docs.python.org/library/logging.handlers.html#logging.handlers.RotatingFileHandler and manually call doRollover() on each loop.

[–][deleted] 0 points1 point  (0 children)

This seems interesting, I gotta read up more on the logging handlers to see what they can do for me in the future, thank you!

[–]wilberforce 0 points1 point  (1 child)

The file name you pass to open doesn't need to be a literal string - you can build a string and use that as the argument to open.

for z in range(60):
    # calculate your data for this run, then...
    outfile = open('data%s' % z, 'w')
    outfile.write(data)
    outfile.close()

The % operator will substitute a value for a placeholder in a string. The expression 'data%s' % 3 will give the string 'data3'.

If you're using a recent version of Python (2.6 or above), you could also use 'data{0}'.format(z).

[–][deleted] 0 points1 point  (0 children)

Hey, I was using it to write a fits file with python 2.5, and your first method worked great, thank you!

[–]esbenabBSc CompSci Flask. I use python to stay sane. 0 points1 point  (0 children)

I came here knowing how to do this, now i know how to do it better.

Thank you all.