CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingMedium

A Python developer is writing a script that needs to create a directory if it doesn't already exist. Which of the following Python code snippets correctly achieves this, preventing an error if the directory already exists?

  1. A```python import os os.mkdir('/tmp/new_dir') ```
  2. B```python import shutil shutil.copytree('/tmp/new_dir', exist_ok=True) ```
  3. C```python import os if not os.path.exists('/tmp/new_dir'): os.mkdir('/tmp/new_dir') ```
  4. D```python import os os.makedirs('/tmp/new_dir', exist_ok=True) ```
Show answer & explanation

Correct answer: D. ```python import os os.makedirs('/tmp/new_dir', exist_ok=True) ```

Option B uses `os.makedirs()` with `exist_ok=True`. This is the most Pythonic and robust way to create a directory, including any necessary parent directories, and it specifically handles the case where the directory already exists without raising an error.

Why the other options are wrong

  • A. `os.mkdir()` will raise an `OSError` if the directory `/tmp/new_dir` already exists, which contradicts the requirement to prevent an error.
  • B. `shutil.copytree()` is used for copying an entire directory tree, not for creating an empty directory. It would also require a source directory to copy from.
  • C. This code snippet works, but `os.makedirs()` with `exist_ok=True` is generally preferred as a more concise and atomic way to achieve the same goal, especially for creating nested directories.

Python Directory Creation (`os.makedirs`)

The `os.makedirs()` function in Python creates directories recursively. The `exist_ok=True` parameter, introduced in Python 3.2, prevents an `OSError` from being raised if the target directory already exists, making it an idempotent way to ensure a directory's presence.

  • `os.makedirs()` creates all necessary parent directories.
  • `exist_ok=True` avoids errors if the directory already exists.
  • `os.mkdir()` only creates a single directory and errors if it exists.

Memory trick: MakeDirs with OK, no error, good to go!

More Automation, Orchestration and Scripting questions