How to Create Folders and Subfolders in Python

Creating and managing folders (also known as directories) is critical when dealing with large applications that require organized storage of files. In this tutorial, we shall delve into the process of creating folders and subfolders in Python. We will make use of the Python os module, a powerful built-in tool for interacting with the operating system.

Step 1: Importing Necessary Modules

To get started, we need to import the os module and the os.path module. These modules are part of the Python Standard Library.

Step 2: Creating a New Folder

To make a new folder, we use the os.mkdir() method.

This snippet will create a folder named “new_folder” in our current directory.

Step 3: Creating a Subfolder

To create a subfolder, we specify a path in the os.mkdir() method.

This will generate a subfolder named “sub_folder” inside the “new_folder” directory.

Step 4: Creating Multiple Subfolders at Once

We can also create several subfolders at once using the os.makedirs() method.

This code creates two subfolders, “sub_folder1” containing “sub_folder2”, under “new_folder”.

Full Code

Please replace the folder names and paths as needed. The code creates folders and subfolders in the current working directory unless a full path is specified.

Conclusion

In this tutorial, we learned how to create folders and subfolders in Python using the os module. This is essential in organizing your files and directories for better management and easy retrieval. Keep practicing this for a more smooth coding experience.