Python: how to safely create directories using the Path class

Python: how to safely create directories using the Path class

In this article we will see how to safely create directories using Python's Path class.

In this article we will see how to safely create directories using Python's Path class.

The mkdir() method of the Path class has the boolean parameter exist_ok. When set to True, if the specified directory already exists in the specified path, the FileExistsError exception is ignored and the directory is overwritten. Conversely, if it is set to False, FileExistsError is raised and the operation fails.

from pathlib import Path

test_dir = Path('./dir')

test_dir.mkdir(exist_ok=True)

In this case even if the directory dir exists, the exception is ignored and the existing directory is overwritten.

Setting this parameter involves our choice of whether or not to preserve an existing directory. If the directory should not be overwritten, then exist_ok should be set to False and we should handle any exceptions that may be raised.