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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.