[Tutor] creating a tab delimited filename
C Smith
smichr at hotmail.com
Tue Mar 15 16:41:35 CET 2005
On Tuesday, Mar 15, 2005, at 05:01 America/Chicago,
tutor-request at python.org wrote:
> how am i going to change the filename automaticaly?
> for example:
> #every 5 minutes, i am going to create a file based on the
> data above
> for i in range(100)
> output_file = file('c:/output' +.join(i) +'.txt', 'w')
> #guess this won't work
> output_file.writelines(lines)
> output_file.close()
>
When faced with this problem, one of the tings that I liked to do was
use a date stamp for the files. The time module has a function called
strftime which allows you to use a template to create a string from the
current time. (See the documentation of python module 'time' for more
details.) e.g.
###
>>> import time
>>> time.strftime('%Y%m%d%H%M')
'200503150934'
###
This string can be added to your 'c:/output' rather than a generic
number like i. Just to be safe you might want to check that the file
doesn't already exist. The nice thing is that there should be few files
that have this number added to them so the loop to get a valid name is
going to succeed quickly.
/c
More information about the Tutor
mailing list