Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 905
guettli Avatar asked Jul 24 '17 14:07

guettli


People also ask

How do I ignore Fileexisterror?

The Python "FileExistsError: [Errno 17] File exists" occurs when we try to create a directory that already exists. To solve the error, set the exist_ok keyword argument to True in the call to the os. makedirs() method, e.g. os. makedirs(dir_name, exist_ok=True) .

Is python2 7 deprecated?

For an additional period of time, you can continue to update existing functions that use the deprecated runtime. For Python 2.7, this period will run until September 30, 2021.

How do I make a directory recursive in Python?

makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os. makedirs() method will create them all. Suppose we want to create directory 'ihritik' but Directory 'GeeksForGeeks' and 'Authors' are unavailable in the path.


2 Answers

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)
like image 120
kichik Avatar answered Oct 17 '22 18:10

kichik


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

import os

if not os.path.exists(path):
    os.makedirs(path)
like image 35
Pat Myron Avatar answered Oct 17 '22 18:10

Pat Myron