Search code examples
python-2.7os.path

How to workaround `exist_ok` missing on Python 2.7?


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.


Solution

  • One way around it is using pathlib. It has a backport for Python 2 and its mkdir() function supports exist_ok.

    try:
      from pathlib import Path
    except ImportError:
      from pathlib2 import Path  # python 2 backport
    
    Path(settings.STATIC_ROOT).mkdir(exist_ok=True)
    

    As the comment suggests, use parents=True for makedirs().

    Path(settings.STATIC_ROOT).mkdir(exist_ok=True, parents=True)