Make multiple directories based on a List using Python
In this article, we are going to learn how to make directories based on a list using Python. Python has a Python 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. Here, we will see how to create nested directories with os.makedirs().
Make Multiple Directories Based on a List in Python
Below are the ways by which we can create multiple directories based on a list in Python:
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.
- Python3
Python3
import os list = [ 'folder10' , 'folder11' , 'folder12' , 'folder13' , 'folder15' ] for items in list : os.mkdir(items) |
Output:
Create a Folder Automatically in Python
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.
- Python3
Python3
import os root_path = 'Documents/tmp/year/month/week/day/hour' list = [ 'car' , 'truck' , 'bike' , 'cycle' , 'train' ] for items in list : path = os.path.join(root_path, items) os.mkdir(path) |
Output:
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.
- Python3
Python3
import os from functools import partial root_directory = 'Documents/abc' list = ( 'one/sub_file_1' , 'two/sub_file_2' , 'three/sub_file_3' ) concat_root_path = partial(os.path.join, root_directory) make_directory = partial(os.makedirs, exist_ok = True ) for path_items in map (concat_root_path, list ): make_directory(path_items) |
Output:
Snapshot of created subfolder given below.
Related Concept
- os Module
- os.mkdir(path)
- os.path.join(root_path, path)
- partial(function,argument1,argument2,…)
- os.makedirs(path)