Python Forum

Full Version: Create dual folder on different path/drive based on the date
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Team,

Below script creates a folder based from a previous date,
My question is,
1. How to declare the if/ else statement that says print("Folder created") else print("Folder already exists")
2. How to create folder in different drives

path = "c:\user\user\My Documents"
path1 = "d:\user\user\backup"

>>> current_time = yesterday.strftime('%Y\%b_%Y\%Y-%m-%d')
>>> print(current_time)
2024\Jan_2024\2024-01-20
>>> command = "mkdir {0}".format(current_time)
>>> print(command)
mkdir 2024\Jan_2024\2024-01-20
This code snippet, from an app that I coded for making backups for files/directories may be of help to you.

for path, dirs, files in walk(SRC):
    for file in files:
        dst_path = Path(path.replace(ROOT, DST))
        if dst_path.exists():
            pass
        else:
            makedirs(dst_path)
        src_path = PurePath(Path(path).joinpath(Path(file)))
        dst_path = PurePath(dst_path.joinpath(Path(file)))
        print(f"Copying {file}")
        RW = read_write(src_path, dst_path)
        COUNT += 1
You'll also need:

from pathlib import Path, PurePath
from os import walk, makedirs

... and also read the docs before you start messing with the file system so that know what you're doing.
Make a function for create folders and don't use singel that way \ in path.
Look into pathlib.
yesterday is not defiend in code.
from pathlib import Path
from datetime import datetime, timedelta

def create_folder(path):
    if not path.exists():
        path.mkdir(parents=True)
        print(f"Folder created: {path}")
    else:
        print(f"Folder already exists: {path}")

if __name__ == '__main__':
    yesterday = datetime.now() - timedelta(days=1)
    folder_name = yesterday.strftime('%Y\%b_%Y\%Y-%m-%d')
    path_c = Path("C:/user/user/My Documents") / folder_name
    path_d = Path("D:/user/user/backup") / folder_name
    create_folder(path_c)
    create_folder(path_d)