Python 3 Examples: Creating, Deleting, Updating directories

Python 3 Examples: Creating, Deleting, Updating directories

Last updated:
Table of Contents

View all code on this jupyter notebook

Create directory if not exists

The intermediate path (/path/to/new) must exist or you'll get an Exception

Use os.mkdir("/path/to/new/directory")

import os

new_directory_path = "/path/to/new/directory"

if not os.path.exists(new_directory_path):
    os.mkdir(new_directory_path)

Mkdir -p Behaviour

I.e. create full path to new directory if it doesn't already exist.

Use os.makedirs("/path/to/new/directory")

import os

new_directory_path = "/path/to/new/directory"

if not os.path.exists(new_directory_path):
    os.makedirs(new_directory_path)

Rm -rf Behaviour

shutil is part of Python's standard library, no need to install anything!

I.e. remove directory recursively including subdirectories, if they exist!

Use shutil.rmtree("/path/to/directory/"):

import os
import shutil

directory_path_to_remove = "/path/to/directory/"

if os.path.exists(directory_path_to_remove):
    shutil.rmtree(directory_path_to_remove)