Languages
[Edit]
EN

Python - create multiple subfolders from list

0 points
Created by:
marc_so
234

In this article, we would like to show you how to create multiple subfolders from a list in Python.

Quick solution:

import os

subfolders = ["subfolder_a", "subfolder_b", "subfolder_c"]

for subfolder_name in subfolders:
    os.makedirs(os.path.join("example_directory", subfolder_name), exist_ok=True)

Note:

The exist_ok parameter was added in Python 3.5. Set it on True so you won't get FileExistsError if the directory exists.

 

Practical example

In this example, we create a directory ("example_directory") with multiple subfolders in our project directory using makedirs() method from os module. The subfolders names will be taken from the list.

import os

subfolders = ["subfolder_a", "subfolder_b", "subfolder_c"]

for subfolder_name in subfolders:
    os.makedirs(os.path.join("example_directory", subfolder_name), exist_ok=True)

if you want to create multiple subfolders outside the project folder, you need to specify the full path:

import os

subfolders = ["subfolder_a", "subfolder_b", "subfolder_c"]

for subfolder_name in subfolders:
    os.makedirs(os.path.join("C:\\some_path\example_directory", subfolder_name), exist_ok=True)

result:

Python - create multiple subfolders from list - before
Python - create multiple subfolders from list - before
Python - create multiple subfolders from list - after
Python - create multiple subfolders from list - after

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join