How to create a Folder in Python
Folders and directories are the same. The directory can be said as a traditional term while a folder is a sort of more familiar name.
Python’s OS module provides many functions for interacting with the operating system. With the help of certain methods available in the OS module we will be able to create a directory. They are:
- os.mkdir()
- os.makedirs()
os.mkdir()
The os.mkdir()
method in Python can be used to create a directory in the specified mode. This method raise FileExistsError
if the directory we are trying to create already exists.
Syntax: os.mkdir(path, mode)
- path: a file system path. it can be either a string or bytes object
- mode (optional): an integer value representing the mode of the directory to be created. default value is Oo777 .
import os directory = "Folder1" parent_dir = "C:/Users/user/Desktop/" path = os.path.join(parent_dir, directory) os.mkdir(path) print("Directory {} is created".format(directory)) directory = "Folder2" parent_dir = "C:/Users/user/Desktop/" path = os.path.join(parent_dir, directory) os.mkdir(path, Oo666) print("Directory {} is created".format(directory))
os.makedirs()
The os.makedirs()
method is used to create a directory recursively. This means that, while making a leaf directory if any intermediate-level directory is missing, os.makedirs()
method will create them all.
Syntax: os.makedirs(path, mode)
- path: a file system path.
- mode (optional): an integer value representing mode. default value is Oo777.
import os # Leaf directory directory = "subfol1" parent_dir = "C:/Users/user/Desktop/Mainfolder/" path = os.path.join(parent_dir, directory) os.makedirs(path) print("Directory {} created" .format(directory)) # Directory 'Mainfolder'will # be created too # if it does not exists # Leaf directory directory = "subfol2" parent_dir = "C:/Users/user/Desktop/Mainfolder/Temp/abc/" path = os.path.join(parent_dir, directory) os.makedirs(path, 0o666) print("Directory {} created" .format(directory))