generate different file name each time you run a program
I have written a script today which has an interesting behavior. Each time the program runs, it generates output in a different file (or in other word, the file name has to be different each time the program runs). So I decided to use current time as the prefix of the filename. I used the localtime() function of time module in Python.
I made a string from localtime and added it before the filename. You can get the idea from the following code block. It's so simple!
Keep enjoying Python!
>>> import time
>>> time.localtime()
(2008, 5, 9, 23, 32, 8, 4, 130, 0)
>>>
I made a string from localtime and added it before the filename. You can get the idea from the following code block. It's so simple!
import time
prefix = ''
for t in time.localtime():
prefix += t.__str__()
fileName = prefix + "_result.csv"
print fileName
Keep enjoying Python!
Comments
TypeError: cannot concatenate 'str' and 'int' objects
By the way, all of this could be avoided by using '%d' % t.
I made the following tests:
>>> x = 12345678909876543210001234567890
>>> x
12345678909876543210001234567890L
>>> x.__str__()
'12345678909876543210001234567890'
>>> y = str(x)
>>> y
'12345678909876543210001234567890'
>>>
Also, look into the 'tempfile' module in python.
prefix=strftime("%Y-%m-%d_%H-%M-%S")
fileName = prefix + "_result.csv"
print fileName
thanks.
Only I'd swap
for t in time.localtime():
prefix += t.__str__()
with
prefix = ''.join([str(t) for t in time.localtime()])
List comprehensions are your friend. :)