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 ?
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)
Just change os.mkdir
to os.makedirs
os.makedirs(today.strftime("%Y/%m/%d"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With