adding current date to a file name in a python script
Fredrik Lundh
fredrik at pythonware.com
Sun Jan 29 04:27:16 EST 2006
markryde at gmail.com wrote:
> I am trying to add the current date to a file name in python script
> like thus:
>
> import os
> import sys
> import rpm
> import time
> import datetime
>
> today = datetime.date.today()
> print "The date is", today
> myFile = '/work/output1'
> myFile = myFile.join(today)
> myFile = myFile.join(".txt")
>
> print "myFile is",myFile
>
>
> running the scripts indeed prints the correct date ,
> but afterwards there is the following error:
>
> The date is 2006-01-29
> Traceback (most recent call last):
> File "addDate.py", line 13, in ?
> myFile = myFile.join(today)
> TypeError: sequence expected, datetime.date found
>
> How should I do this ?
datetime.date.today() returns a date object, not a string.
if the default string conversion is what you want, use str(today) to
convert to a string.
also note that "join" doesn't do what you think it does; "x.join(y)"
joins all members of the sequence y (which must all be strings) using
x as the separator. this gives you a filename like
'.2/work/output10/work/output10/work/output16/work/output1-/work/output10/work/o
utput11/work/output1-/work/output12/work/output19t2/work/output10/work/output10/
work/output16/work/output1-/work/output10/work/output11/work/output1-/work/outpu
t12/work/output19x2/work/output10/work/output10/work/output16/work/output1-/work
/output10/work/output11/work/output1-/work/output12/work/output19t'
which is probably not what you want.
to fix this, you can use +=
myFile = '/work/output1'
myFile += str(today)
myFile += ".txt"
or % formatting:
myFile = '/work/output1%s.txt' % today
(here, "%s" does the str() call for you).
</F>
More information about the Python-list
mailing list