In this article, we are going to learn how to make directories based on a list using Python. Python has the module named os which forms the core part of the python ecosystem. The os module helps us to work with operating system folders and other related functionalities. Although we can make folders/directories directly on the system here we will see how to make many folders from a list given in python which is less time-consuming.
To do our task, we will use some modules and their methods provided in Python which are as follows:
- os: The os module in python provide us some methods for interacting with the operating system(here for creating the folders).
- os.mkdir(path): Used to create a single folder(here path) at a time in a directory.
- os.path.join(root_path, path): This method concatenates several paths to a single directory. Here the parameters root path will be concatenated with the path want to create.
- partial(function,argument1,argument2,…): This method permits one to fix certain number of arguments and generate a new function.
- os.makedirs(path): This method helps us to create multiple directories at once. Here the parameter path indicates the directory with sub folders we want to create.
Example 1: Create folders in the same directory where Python is installed
In this example, we have taken a list of elements. Then we iterate through each element in the list. Since we have not mentioned any root directory, the os module makes a folder of each element of the list in the directory where our python ide is installed.
Example 2: Create files in a different directory
Declare the root directory where we want to create the list of folders in a variable. Initialize a list of items. Then iterate through each element in the list. The os module makes a folder of each element of the list in the directory where our python ide is installed. Use os.path.join() to join the items of the list as a folder to the root directory. Then use os.mkdir() to create a single directory in each iteration through the list.
Example 3: Create a list of directories with subfolders inside a given root directory
First, import the partial function from the functions module and initialize the root directory and list of directories. Use the partial function and pre-fill it with the root directory to create the path for creating a list of folders inside. Then again with the help of partial function and os.makedirs() method prefills the make_directory function. Iterate through the list of items given. In each iteration call the make_directory method with each list item as a parameter to create a directory.
Snapshot of created subfolder given below.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course