![]() |
VOOZH | about |
Creating a nested directory in Python involves ensuring that the directory is created safely, without overwriting existing directories or causing errors. To create a nested directory we can use methods like os.makedirs(), os.path.exists(), and Path.mkdir(). In this article, we will study how to safely create a Nested Directory in Python.
Below are some of the ways and approaches by which we can create a Nested Directory using Python:
In this example, os.makedirs() function is used to create a nested directory. It accepts the path of the directory to be created as input. If the directory already exists, it raises a FileExistsError and prints a message indicating that the directory already exists but if the directory does not exist, it creates it and prints a success message.
Directory './parent_directory/child_directory' created successfully.
In this example, os.path.exists() function is used to checks if the directory already exists and if it does not exist than it creates it using os.makedirs().
Directory './parent_directory/child_directory' created successfully.
In this example, path.mkdir() method from the pathlibmodule is used to create a directory.It accepts the path of the directory to be created as input.It checks if parents argument is set to True thus creating parent directories if they do not exists but If the directory already exists, it raises a FileExistsError, which is caught by the except block
Directory './parent_directory/child_directory' created successfully.