Using variables in creating a file name
Question: I'm pretty new to python, and am wondering if there's any way to put a
variable into a file name, so that you can create files with different names
each time.

In my particular case, I'd like to add date and time to the file name. If it
was possible, this would work perfectly:

    
    
    example = open("Path/to/file%s", "w") % str(datetime.now())
    

...but it doesn't. Is there any way to get that sort of functionality using a
different approach? I've tried searching for an answer either way using
multiple phrasings, but I can't find a yea or nay on it.

Thanks in advance guys.

EDIT: That was supposed to be an open() function, adjusted accordingly.


Answer: This should work. `format()` will replace the placeholder `{0}` in the string
with the formatted `datetime` string (`datestr`).

    
    
    >>> from datetime import datetime
    >>> datestr = datetime.strftime(datetime.today(), "%Hh %Mm %Ss %A, %B %Y")
    >>> examplefile = open("/home/michael/file{0}".format(datestr), 'w')
    >>> print(examplefile)
    <open file '/home/michael/file21h 20m 34s Monday, September 2012', mode 'w' at 0x89fcf98>
    

