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.

>>> 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

aatiis said…
I like to use `t` instead of t.__str__().
Tamim Shahriar said…
but 't' is 'int' type, so we have to convert it to 'string' before appending it to another string, if do don't (just use 't'), the following error message is shown:

TypeError: cannot concatenate 'str' and 'int' objects
aatiis said…
I meant `t`, those are not apostrophes, but those signs above the 'tilda' (~) sign on the keyboard. It's safe when using small numbers, but watch out with longs, or you'll get a 'L' at the end of the string.
By the way, all of this could be avoided by using '%d' % t.
Tamim Shahriar said…
Ya, I understand, only t :)

I made the following tests:

>>> x = 12345678909876543210001234567890
>>> x
12345678909876543210001234567890L
>>> x.__str__()
'12345678909876543210001234567890'
>>> y = str(x)
>>> y
'12345678909876543210001234567890'
>>>
aatiis said…
Yeah, you were right. Actually I think `y` is short for y.__repr__(), rather than y.__str__() (which is the same in many cases, but not all.) Thanks for pointing that out.
Casey said…
use str(t).

Also, look into the 'tempfile' module in python.
Daniel Garcia said…
from time import strftime

prefix=strftime("%Y-%m-%d_%H-%M-%S")

fileName = prefix + "_result.csv"

print fileName
Tamim Shahriar said…
ya, it's more Pythonic :)
thanks.
Waiz said…
Nice!

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. :)
Attila Oláh said…
Waiz, I see you having a point here :)
SUMOD SUNDAR said…
Can anybody say how to get unicode of characters with utf-8 coding using python?

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code