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.
1 |
import os |
Step 2: Creating a New Folder
To make a new folder, we use the os.mkdir() method.
1 |
os.mkdir('new_folder') |
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.
1 |
os.mkdir('new_folder/sub_folder') |
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.
1 |
os.makedirs('new_folder/sub_folder1/sub_folder2') |
This code creates two subfolders, “sub_folder1” containing “sub_folder2”, under “new_folder”.
Full Code
1 2 3 4 5 6 7 8 9 10 |
import os # create a new folder os.mkdir('new_folder') # create a sub_folder os.mkdir('new_folder/sub_folder') # create multiple subfolders at once os.makedirs('new_folder/sub_folder1/sub_folder2') |
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.