Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 280
Jecki Avatar asked Dec 19 '22 21:12

Jecki


2 Answers

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)
like image 60
Torxed Avatar answered Dec 21 '22 11:12

Torxed


Just change os.mkdir to os.makedirs

os.makedirs(today.strftime("%Y/%m/%d"))
like image 43
Valijon Avatar answered Dec 21 '22 11:12

Valijon