How do you combine strings and string variables in python

110 views Asked by At

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.

3

There are 3 answers

6
kirbyfan64sos On BEST ANSWER

You can use str.format:

f = open("{}/{}/{}.txt".format(date, month, week),"a")

I suggest you finish the Python tutorial before trying anything too ambitious!

0
John Ruddell On

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

5
TigerhawkT3 On

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.