preethy tulpi
preethy tulpi

Reputation: 415

Create directory recursively in python for linux

I am trying to create directory recursively using a Python script, but am getting and error.

Code:

import os
a = "abc"
os.makedirs('/root/test_{}'.format(a), exist_ok=True)

Error:

Traceback (most recent call last):
  File "mk.py", line 3, in <module>
    os.makedirs('/root/test_{}'.format(a), exist_ok=True)
  TypeError: makedirs() got an unexpected keyword argument 'exist_ok'

I am using python2.7 and the above option does not work in this version? If not, what is alternate solution?

Upvotes: 1

Views: 2891

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49814

os.makedirs() is the correct function, but is has no parameter exist_ok in Python 2. Instead use os.path.exists() like:

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

Be aware that this does not exactly match the bahavior of the exist_ok flag in Python3. Closer to matching that would be something like:

if os.path.exists(path_to_make):
    if not os.path.isdir(path_to_make):
        raise OSError("Cannot create a file when that file already exists: "
                      "'{}'".format(path_to_make))
else:
    os.makedirs(path_to_make)

Upvotes: 3

Related Questions