1

I want to create multiple folders within themselves. If I have 3 folder I want to make on my desktop nested within each other. I want create the directory 'C:/Users/User/Desktop/folder_a/folder_b/folder_c/' the way I currently do this is I call os.path.exists() and os.mkdir() multiple times. Is there a way to do this without having to call these multiple times?

import os

DIR = 'C:/Users/User/Desktop/folder_a/folder_b/folder_c/'
if not os.path.exists(DIR):
    os.mkdir(DIR)
DIR = DIR + 'folder_b/'
if not os.path.exists(DIR):
    os.mkdir(DIR)
DIR = DIR + 'folder_c/'
if not os.path.exists(DIR):
    os.mkdir(DIR)
1

2 Answers 2

2

So we only need to do one check :) As folder_b can not exist if folder_a is not present.

Which brings us to the 2nd scenario. For which we leave out exist_ok=True for the appropriate check to be made again, but for the inclusion of folder_b and 'folder_c' if neither exist.

Option 1:

from os import (
    makedirs,
    path,
)

dir_path = 'C:/Users/User/Desktop/folder_a/{}'

if path.exists(dir_path):
    makedirs(
        dir_path.format(
            'folder_b/folder_c/',
        )
    )

Option 2:

from os import makedirs

dir_path = 'C:/Users/User/Desktop/folder_a/folder_b/folder_c'
makedirs(dir_path)
Sign up to request clarification or add additional context in comments.

Comments

1

I wrote a recursive function for you:

import os

DIR = './folder_a/folder_b/folder_c/'

def make_nested_folders(DIR):
  print(DIR)
  if "/" in DIR:
    DIR, last = DIR.rsplit("/", 1)
    make_nested_folders(DIR)
  else:
    last = DIR
  if last and not os.path.exists(last):
    os.mkdir(last)

make_nested_folders(DIR)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.