1

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?

1
  • 2
    exist_ok is "new" in version 3.2 Commented Jan 15, 2018 at 4:07

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

7 Comments

No, this has not the same behaviour.
@wim, Really? Why not? What am I missing?
For example if a file with the name exists (not a directory).
Doesn't that check technically get applied to every part of the path.
This code has a race condition (another process could execute a system call between the system calls from this process to check for existence and for creating an entry). A more robust approach is to just attempt to create eaoh directory, and catch the error for "directory already exists". Handling "name exists but isn't a directory" is an interesting challenge.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.