import os # Create a directory named "mydir" in the current directory os.makedirs('mydir') # Create a subdirectory named "mysubdir" inside "mydir" os.makedirs('mydir/mysubdir')
To safely create a nested directory in Python, you can use the os.makedirs() function from the os module. This function takes a single argument, which is the name of the directory to create, and creates all of the intermediate directories in the path if they do not already exist.
In this example, the os.makedirs() function is used to create a directory named mydir in the current directory, and then a subdirectory named mysubdir inside mydir. If either of these directories already exists, the os.makedirs() function will not raise an error, and will instead return silently.
The os.makedirs() function is a safe and convenient way to create nested directories in Python. It ensures that all of the intermediate directories in the path are created, and it does not raise an error if the directories already exist. This makes it easier to write code that creates directories without having to check if they already exist first.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.