Reputation: 208
If the path doesn't exists the code working fine but when year(2021) folder exists it just stops working after the first condition
def check_path():
from datetime import datetime, timedelta
dt = datetime.today()
year = str(dt.year)
month = str(dt.month)
day = str(dt.day)
path = os.path.join( year)
if not os.path.exists(path):
os.mkdir(path)
path = os.path.join(path, month)
if not os.path.exists(path):
os.mkdir(path)
path = os.path.join(path, day)
if not os.path.exists(path):
os.mkdir(path)
The final result I want it is //2021//08//26 folders created
Upvotes: 1
Views: 2526
Reputation: 4510
For linux should work for you:
import os
import time
os.makedirs(f'/folder/root/{time.strftime("/%Y/%m/%d")}', exist_ok=True)
If you want to create folder in file directory path then you can use following code:
import os
import time
current_dir = os.getcwd()
os.makedirs(f'{current_dir}/{time.strftime("/%Y/%m/%d")}', exist_ok=True)
Upvotes: 0
Reputation: 87
You used nested conditions... So, Put conditions as below to achieve your desired output:
if not os.path.exists(path):
os.mkdir(path)
path = os.path.join(path, month)
if not os.path.exists(path):
os.mkdir(path)
path = os.path.join(path, day)
if not os.path.exists(path):
os.mkdir(path)
Upvotes: 1
Reputation:
I recommend using Path from path lib like this:-
from pathlib import Path
from datetime import datetime
t = datetime.today()
basedir = '/Users/andy'
Path(f'{basedir}/{t.year}/{t.month:02d}/{t.day:02d}').mkdir(parents=True, exist_ok=True)
Note: This is for Unix type systems. For Windows adjust path separator appropriately
Upvotes: 5