Jecki
Jecki

Reputation: 802

python create directory structure based on the date

I used the following function to created dirctory based on today date ,

#!/usr/bin/python
import time, datetime, os

today = datetime.date.today()  

todaystr = today.isoformat()   

os.mkdir(todaystr)

so the out put will be

/2015-12-22/

what i'm looking to is adjust the structure which is create dirctories structure based on day date as following

/2015/12/22
/2015/12/23
etc 

when ever i run the function it will check the date and make sure the folder is exist other wise will create it .. any tips to follow here ?

Upvotes: 5

Views: 15765

Answers (2)

Torxed
Torxed

Reputation: 23480

Consider using strftime instead. Which you can use to defined a format to your liking. You will also need to use os.makedirs as described by @Valijon below.

os.makedirs(time.strftime("/%Y/%m/%d"), exist_ok=True)

You can also append a given time to create a time-stamp in the past or in the future.

time.strftime("/%Y/%m/%d", time.gmtime(time.time()-3600)) # -1 hour

Also note that your path is a bit dangerous, unless you want to create folders directly under the root partition.

Note that makedirs will raise an exception by default if the directory already exists, you can specify exist_ok=True to avoid this, read more about it in the docs for os.makedirs.


Since Python 3.4, the module pathlib was Introduced which offers some directory and file creation features.

import time
import pathlib
pathlib.Path(time.strftime("/%Y/%m/%d")).mkdir(parents=True, exist_ok=True)

Upvotes: 12

Valijon
Valijon

Reputation: 13103

Just change os.mkdir to os.makedirs

os.makedirs(today.strftime("%Y/%m/%d"))

Upvotes: 2

Related Questions