Here are two ways to create a folder in the current working directory in Python:
- Using os.mkdir()
- Using os.makedirs()
Method 1: Using os.mkdir()
The os.mkdir() method is used to create a folder in the current working directory. It creates only the final target directory and will fail if the parent directory doesn’t exist.
Here is the current working directory before creating a new folder:
import os
# Define the name of the directory to be created
folder_name = "new_dir"
path = os.path.join(".", folder_name) # Path relative to the current directory
try:
os.mkdir(path)
print(f"Directory '{folder_name}' created.")
except FileExistsError:
print(f"Directory '{folder_name}' already exists.")
Output
Directory 'new_dir' created.
Method 2: Using os.makedirs()
The os.makedirs() method is similar to os.mkdir(), but it can also create intermediate directories if they don’t exist. This is helpful if you need to create a nested directory structure in one go.
import os
# Define the name of the nested directory to be created
nested_folder = "./nested/sub_folder"
try:
# 'exist_ok=True' prevents an error if the directory already exists
os.makedirs(nested_folder, exist_ok=True)
print(f"Nested directories '{nested_folder}' created.")
except FileExistsError:
print(f"Directory '{nested_folder}' already exists.")
Output
Nested directories './nested/sub_folder' created.
In this example, os.makedirs() function creates both new_folder and sub_folder if they don’t exist.
The exist_ok=True parameter allows the function to complete successfully even if the directories already exist, preventing a FileExistsError.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.