Create a directory in Python - GeeksforGeeks (2024)

Last Updated : 29 Dec, 2020

Comments

Improve

The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The os and os.path modules include many functions to interact with the file system. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.

There are different methods available in the OS module for creating a director. These are –

  • os.mkdir()
  • os.makedirs()

Using os.mkdir()

os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raise FileExistsError if the directory to be created already exists.

Syntax: os.mkdir(path, mode = 0o777, *, dir_fd = None)

Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
mode (optional): A Integer value representing mode of the directory to be created. If this parameter is omitted then default value Oo777 is used.
dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.
If the specified path is absolute then dir_fd is ignored.

Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.

Return Type: This method does not return any value.

Example #1: Use of os.mkdir() method to create directory/file

# Python program to explain os.mkdir() method

# importing os module

import os

# Directory

directory = "GeeksforGeeks"

# Parent Directory path

parent_dir = "D:/Pycharm projects/"

# Path

path = os.path.join(parent_dir, directory)

# Create the directory

# 'GeeksForGeeks' in

# '/home / User / Documents'

os.mkdir(path)

print("Directory '% s' created" % directory)

# Directory

directory = "Geeks"

# Parent Directory path

parent_dir = "D:/Pycharm projects"

# mode

mode = 0o666

# Path

path = os.path.join(parent_dir, directory)

# Create the directory

# 'GeeksForGeeks' in

# '/home / User / Documents'

# with mode 0o666

os.mkdir(path, mode)

print("Directory '% s' created" % directory)

Output:

Directory 'GeeksforGeeks' createdDirectory 'Geeks' created

Example #2: Errors while using os.mkdir() method.

# Python program to explain os.mkdir() method

# importing os module

import os

# Directory

directory = "GeeksForGeeks"

# Parent Directory path

parent_dir = "D:/Pycharm projects/"

# Path

path = os.path.join(parent_dir, directory)

# Create the directory

# 'GeeksForGeeks' in

# '/home / User / Documents'

os.mkdir(path)

print("Directory '% s' created" % directory)

# if directory / file that

# is to be created already

# exists then 'FileExistsError'

# will be raised by os.mkdir() method

# Similarly, if the specified path

# is invalid 'FileNotFoundError' Error

# will be raised

Output:

Traceback (most recent call last): File "gfg.py", line 18, in  os.mkdir(path)FileExistsError: [WinError 183] Cannot create a file when that file / /already exists: 'D:/Pycharm projects/GeeksForGeeks'

Example #3: Handling error while using os.mkdir() method.

# Python program to explain os.mkdir() method

# importing os module

import os

# path

path = 'D:/Pycharm projects / GeeksForGeeks'

# Create the directory

# 'GeeksForGeeks' in

# '/home / User / Documents'

try:

os.mkdir(path)

except OSError as error:

print(error)

Output:

[WinError 183] Cannot create a file when that file/ /already exists: 'D:/Pycharm projects/GeeksForGeeks'

Using os.makedirs()

os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.
For example, consider the following path:

D:/Pycharm projects/GeeksForGeeks/Authors/Nikhil

Suppose we want to create directory ‘Nikhil’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directories in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘Nikhil’ directory will be created.

Syntax: os.makedirs(path, mode = 0o777, exist_ok = False)

Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
mode (optional): A Integer value representing mode of the newly created directory. If this parameter is omitted then the default value Oo777 is used.
exist_ok (optional): A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not.

Return Type: This method does not return any value.

Example #1: Use of os.makedirs() method to create directory.

# Python program to explain os.makedirs() method

# importing os module

import os

# Leaf directory

directory = "Nikhil"

# Parent Directories

parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"

# Path

path = os.path.join(parent_dir, directory)

# Create the directory

# 'Nikhil'

os.makedirs(path)

print("Directory '% s' created" % directory)

# Directory 'GeeksForGeeks' and 'Authors' will

# be created too

# if it does not exists

# Leaf directory

directory = "c"

# Parent Directories

parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b"

# mode

mode = 0o666

path = os.path.join(parent_dir, directory)

# Create the directory 'c'

os.makedirs(path, mode)

print("Directory '% s' created" % directory)

# 'GeeksForGeeks', 'a', and 'b'

# will also be created if

# it does not exists

# If any of the intermediate level

# directory is missing

# os.makedirs() method will

# create them

# os.makedirs() method can be

# used to create a directory tree

Output:

Directory 'Nikhil' createdDirectory 'c' created

Example #2:

# Python program to explain os.makedirs() method

# importing os module

import os

# os.makedirs() method will raise

# an OSError if the directory

# to be created already exists

# Directory

directory = "Nikhil"

# Parent Directory path

parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"

# Path

path = os.path.join(parent_dir, directory)

# Create the directory

# 'Nikhil'

os.makedirs(path)

print("Directory '% s' created" % directory)

Output:

Traceback (most recent call last): File "gfg.py", line 22, in  os.makedirs(path) File "C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python/ / \Python38-32\lib\os.py", line 221, in makedirs mkdir(name, mode)FileExistsError: [WinError 183] Cannot create a file when that/ / file already exists: 'D:/Pycharm projects/GeeksForGeeks/Authors\\Nikhil'

Example #3: Handling errors while using os.makedirs() method.

# Python program to explain os.makedirs() method

# importing os module

import os

# os.makedirs() method will raise

# an OSError if the directory

# to be created already exists

# But It can be suppressed by

# setting the value of a parameter

# exist_ok as True

# Directory

directory = "Nikhil"

# Parent Directory path

parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"

# Path

path = os.path.join(parent_dir, directory)

# Create the directory

# 'Nikhil'

try:

os.makedirs(path, exist_ok = True)

print("Directory '%s' created successfully" % directory)

except OSError as error:

print("Directory '%s' can not be created" % directory)

# By setting exist_ok as True

# error caused due already

# existing directory can be suppressed

# but other OSError may be raised

# due to other error like

# invalid path name

Output:

Directory 'Nikhil' created successfully


N

nikhilaggarwal3

Improve

Next Article

Get Current directory in Python

Please Login to comment...

Create a directory in Python - GeeksforGeeks (2024)

FAQs

Create a directory in Python - GeeksforGeeks? ›

mkdir() method in Python is used to create a directory in Python or create a directory with Python named path with the specified numeric mode. This method raises FileExistsError if the directory to be created already exists.

How to create a directory in Python? ›

The os. mkdir() method in Python creates a new directory (folder). It belongs to the os module, which provides a way to interact with the operating system.

How do I create a current directory in Python? ›

As you see, you can get the current working directory in Python by importing the os module and calling the os. getcwd() method. You can change the working directory using the os. chdir(<path>) method, and you can test whether a path, either directory, or file, exists using the os.

What is mkdir() in Python? ›

mkdir() method is used to create a directory. If the directory already exists, FileExistsError is raised. Note: Available on WINDOWS and UNIX platforms.

How do you create a directory exists in Python? ›

exists() function is used to check if the directory already exists. If the directory does not exist, the os. makedirs() function is used to create it.

How to create a directory? ›

To create new directory use "mkdir" command. For example, to create directory TMP in the current directory issue either "mkdir TMP" or "mkdir ./TMP". It's a good practice to organize files by creating directories and putting files inside of them instead of having all files in one directory.

What is a directory in Python? ›

Directories are a way of storing, organizing, and separating the files on a computer. The directory that does not have a parent is called a root directory. The way to reach the file is called the path.

How do you set directory in Python? ›

You can change (set) the current working directory with os. chdir() . os. chdir() changes the current directory, similar to the Unix command cd .

How to create an output directory in Python? ›

In Python, we can make a new directory using the mkdir() method. This method takes in the path of the new directory. If the full path is not specified, the new directory is created in the current working directory.

How do I write a mkdir command? ›

The basic syntax for using this command is mkdir {dir} (replace {dir} with the desired name of your directory). Before creating any directory or file, remember that most Linux filesystems are case-sensitive.

Does directory exist in Python? ›

To check if a file or directory already exists in Python, you can use the following methods: os. path. exists(path): Checks if a file or directory exists at the given path.

How do you get the directory in Python? ›

There are a couple of ways to get the current working directory in Python:
  1. By using the os module and the os. getcwd() method.
  2. By using the pathlib module and the Path. cwd() method.
Mar 28, 2023

How do you check for a directory and create it in Python? ›

In Python, use the os. path. exists() method to see if a directory already exists, and then use the os. makedirs() method to create it.

How to add directory path in Python? ›

How to Add Python to PATH on Windows
  1. Step 1: Find Python Installation Directory. Before modifying the PATH variable, find the Python installation directory. ...
  2. Step 2: Locate PATH Variable Options. ...
  3. Step 3: Add Python Directory to PATH.
Dec 28, 2023

How do I create a directory package in Python? ›

To tell Python that a particular directory is a package, we create a file named __init__.py inside it and then it is considered as a package and we may create other modules and sub-packages within it.

How do you create a directory and subdirectory in Python? ›

To safely create a nested directory in Python, you can use the os. makedirs() function from the os module. This function takes a single argument, which is the name of the directory to create, and creates all of the intermediate directories in the path if they do not already exist.

Top Articles
Boruto: Kawaki's Tragic Past, Explained
M&T Bank Holiday Schedule 2022
Texas Roadhouse On Siegen Lane
Grizzly Expiration Date 2023
Arcanis Secret Santa
Papa's Pizzeria - Play Online at Coolmath Games
Charli D'Amelio: Wie die junge Amerikannerin TikTok-Sensation wurde
Jeff Siegel Picks Santa Anita
Chukchansi Webcam
Hill & Moin Top Workers Compensation Lawyer
1 Bedroom Apartment For Rent Private Landlord
Ge Tracker Awakener Orb
Fintechzoommortgagecalculator.live Hours
Aly Raisman Nipple
Sermon Collections, Sermons, Videos, PowerPoint Templates, Backgrounds
Summoner Weapons Terraria
Stephjc Forum
Post Crescent Obituary
Rantingly App
Sm64Ex Coop Mods
895 Area Code Time Zone
Devotion Showtimes Near Regency Towngate 8
Kim Dotcom to fight extradition, says he won't get fair trial in US
Gulfport Senior Center Calendar
Infinity Pool Showtimes Near Cinemark 14 Chico
Jesus Revolution (2023)
Cal Poly 2027 College Confidential
Union Supply Direct Wisconsin
Dicks Sporting Good Lincoln Ne
Publix Christmas Dinner 2022
Kltv Com Big Red Box
Storenet Walgreens At Home
Hanging Hyena 4X4
Classy Spa Fort Walton Beach
Clothes Mentor Overland Park Photos
Lowes Light Switch
Peoplesgamezgiftexchange House Of Fun Coins
1875 Grams To Pounds And Ounces
Cavender's Boot City Lafayette Photos
How to Get Rid of Phlegm, Effective Tips and Home Remedies
Fedex Express Location Near Me
Degreeworks Sbu
Mosley Lane Candles
Ccga Address
Strange World Showtimes Near Amc Marquis 16
Currently Confined Coles County
Sams Warehouse Jobs
Ava Kayla And Scarlet - Mean Bitches Humiliate A Beta
June 21 2019 Algebra 2 Regents Answers
Gotham Chess Twitter
Lhhouston Photos
Does Speedway Sell Elf Bars
Latest Posts
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 6402

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.