create a python directory code example

Example 1: python create directory

# This requires Python’s OS module
import os

# 'mkdir' creates a directory in current directory.
os.mkdir('tempDir') 
# can also be used with a path, if the other folders exist.
os.mkdir('tempDir2/temp2/temp')

# 'makedirs' creates a directory with it's path, if applicable.
os.makedirs('tempDir2/temp2/temp')

Example 2: create a directory python

#creates a directory without throwing an error
import os
def create_dir(dir):
  if not os.path.exists(dir):
    os.makedirs(dir)
    print("Created Directory : ", dir)
  else:
    print("Directory already existed : ", dir)
  return dir

Example 3: how to add directory to python script

import os

# List all files in a directory using scandir()
basepath = 'my_directory/'
with os.scandir(basepath) as entries:
    for entry in entries:
        if entry.is_file():
            print(entry.name)