Home » Python

Create a nested directory in Python

Creating a nested directory: Here, we are going to learn how to create a nested directory in Python programming language using OS and Pathlib modules?
Submitted by Sapna Deraje Radhakrishna, on October 22, 2019

Creating multiple or nested directories in python should be implemented considering various error scenarios like,

  1. Does the parent directory exist?
  2. What if the nested directories already exist?

Using OS Module

The most common module used in any file system operation is the os module. Using the os module, it is easy to work with the file system. Consider the below example which creates the nested directory which also evaluates the error scenario to ensure the code is not error or failure-prone.

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import os
>>> directory_to_be_created = 'test/include/help'
>>> os.makedirs(directory_to_be_created, exist_ok=True)
>>>

The keyword exist_ok is an optional argument with default value as False. This keyword is only available in 3.2+. This keyword ensures that the exception is not raised if the directory already exists.

Using Pathlib Module

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import pathlib
>>> pathlib.Path('test_1/directory').mkdir(parents=True, exist_ok=True)

In the above example, pathlib.Path.mkdir recursively creates the directory and does not raise an exception if the directory already exists.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.