Safely creating a folder if it doesn't exist

Safely creating a folder if it doesn't exist

When you are writing to files in python, if the file doesn't exist it will be created. However, if you are trying to write a file in a directory that doesn't exist, an exception will be returned

FileNotFoundError: [Errno 2] No such file or directory: "directory"

This article will teach you how to make sure the target directory exists. If it doesn't, the function will create that directory.

First, let's import os and make sure that the "test_directory" doesn't exist

import os 

os.path.exists(".\\test_directory")
False

copy the ensure_dir function in your code. This function will handle the creation of the directory. Credit goes to Parand posted on StackOverflow

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

Let's now use the function and create a folder named "test_directory"

ensure_dir(".\\test_directory")

If we test for the existence of the directory, the exists function will now return True

os.path.exists(".\\test_directory")
True