I'm trying to open a text file with a dynamic path. How could I make it work something like this?:
f = open("date/month/week.txt","a")
date, month, and week are the current date, month, and week.
I'm trying to open a text file with a dynamic path. How could I make it work something like this?:
f = open("date/month/week.txt","a")
date, month, and week are the current date, month, and week.
you can try this. using string format and datetime for a complete solution
d = datetime.datetime.today()
date = d.date()
month = d.month
week = d.isocalendar()[1]
f = open('{date}/{month}/{week}.txt'.format(date=date, month=month, week=week),"a")
my personal preference on the naming convention for dates and a file would be in the format 'yyyy-mm-dd' you can include the week on this too, which would look like this
d = datetime.datetime.today()
date = d.date()
week = d.isocalendar()[1]
f = open('{date}-{week}.txt'.format(date=date, week=week),"a")
that would result in a file of this format. 2015-06-08-24.txt
Use the datetime
module with strftime
formatting.
import datetime
f = open(datetime.datetime.strftime(datetime.datetime.now(), '%d/%m/%U') + '.txt', 'a')
For a date of June 8, 2015, this creates a filename of 08/06/23.txt
.
You can use
str.format
:I suggest you finish the Python tutorial before trying anything too ambitious!