Working With Directories in Python

Last modified: 
Monday, March 30th, 2015

Overview

This page outlines some techniques for working with directories in Python.

Creating Directories

How to create new directory in Python

import os, errno

path = '/path/to/new/directory'
os.makedirs(path)

How to create an entire directory structure

import os, errno

#
# Mimic behavior BASH mkdir -p in older versions of Python
# http://stackoverflow.com/a/600612
#
def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError, exc: # Python <= 2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else: raise


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.