How does mkdir -p work in Python?

PythonServer Side ProgrammingProgramming

A directory in Python is defined as collection of multiple files and sub-directories. And by using mkdir –p command we are going to create sub-directories of a directory. If the parent directory doesn’t exist, the command will create parent directory first; but if it already exists any error message isn’t thrown. Instead, the command will move forward to create sub directories.

┌──(tutorialspoint㉿kali)-[~/Desktop] └─$ ls code.py ###There is no directory ┌──(tutorialspoint㉿kali)-[~/Desktop] └─$ mkdir -p tutorialspoint/python/tutorials ###Creation of directory using mkdir -p ┌──(tutorialspoint㉿kali)-[~/Desktop] └─$ cd tutorialspoint/python/tutorials ###Changing to created directory ┌──(tutorialspoint㉿kali)-[~/Desktop/tutorialspoint/python/tutorials] └─$ pwd /home/govind/Desktop/tutorialspoint/python/tutorials ###Directory created

Using os Module

Python programming language provides an os module that allows to perform various operations on the directories and the files within those directories. This module provides a portal to perform all the operating system dependent functionalities through python; performing file operations, manipulating paths, working with directories etc.

Example

Using the following code, we are going to make a new directories using mkdir -p and importing OS module in python. This code will create a parent directory with sub directories.

import os def mkdirp( path ): try: os.makedirs( path ) except OSError: if not os.path.isdir( path ): raise mkdirp( '/home/govind/Desktop/tutorialspoint/python/article' )

Output

By executing above code we created a parent folder with name “tutorialspoint” and “python” and “article” as sub directories.

┌──(tutorialsPoint㉿kali)-[~/Desktop]
└─$ ls
code.py

┌──(tutorialsPoint㉿kali)-[~/Desktop]
└─$ sudo python code.py

┌──(tutorialsPoint㉿kali)-[~/Desktop]
└─$ ls
code.py tutorialspoint
raja
Updated on 10-Oct-2022 09:13:28

Advertisements