How to workaround `exist_ok` missing on Python 2.7?

Viewed 17106

On Python 2.7 os.makedirs() is missing exist_ok. This is available in Python 3 only.

I know that this is the a working work around:

try:
    os.makedirs(settings.STATIC_ROOT)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

I could create a custom my_make_dirs() method and use this, instead of os.makedirs(), but this is not nice.

What is the most pythonic work around, if you forced to support Python 2.7?

AFAIK python-future or six won't help here.

4 Answers

You could call makedirs() after checking that the path does not exist:

import os

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

The accepted answer incomplete as os.makedirs() creates subfolders recursively and Path.mkdir(), like os.mkdir(), can only create new directory in an existing place. Another approach is to leverage exceptions thrown to distinguish and tolerate behaviors between Python2/3.

import errno
import os
import os.path

def makedirs(folder, *args, **kwargs):
  try:
    return os.makedirs(folder, exist_ok=True, *args, **kwargs)
  except TypeError: 
    # Unexpected arguments encountered 
    pass

  try:
    # Should work is TypeError was caused by exist_ok, eg., Py2
    return os.makedirs(folder, *args, **kwargs)
  except OSError as e:
    if e.errno != errno.EEXIST:
      raise

    if os.path.isfile(folder):
      # folder is a file, raise OSError just like os.makedirs() in Py3
      raise

Also see: Python "FileExists" error when making directory

Related