How to Create a Directory in Python - AskPython (2024)

Python was used to create a wide variety of applications, some of which required the creation of a directory to run on the system. For example, if you are installing an application, you see that many directories are automatically created to store that application data, you don’t need to create that.

In the same way, you can write code to create the directories and put that in your application so that it can create directories automatically to store data.

In this tutorial, we will see how to do precisely that. We will learn several ways to create a directory in Python.

Steps to Create a Directory in Python

Python os module is a module used to deal with and interact with the underlying operating systems and the files.

The os module contains various in-built methods to create directories in the system. Among them, the popular ones are the mkdir() method and the makedirs() method in Python.

To use os module methods, we need to import it using the below syntax:

import os 

Now, once you have imported it into your Python project, you can use its methods mkdir() and makedirs() to create a directory, let’s go through them one by one so that you can choose them accordingly.

Using os.mkdir() method to Create a Directory in Python

The mkdir() method is used to create a directory on a specific path, if any of the parent directories are not present as mentioned in the path, then this method throws an error “FileNotFoundError”.

This is why mkdir() method is recommended to use only in places where you are sure that the directories mentioned in the specified path are already present.

Syntax:

os.mkdir(path, mode)
  • path: The location wherein the user wants the directory to be created. It is a string or byte value that includes the entire path and name of the directory to be built.
  • mode: The permissions that must be given to deal with the file operations within the directory. The default value is ‘0o777‘.

Example 1: Create a Directory using Python in the specified location.

 import os main_dir = "C:/Practice"os.mkdir(main_dir) print("Directory '% s' is built!" % main_dir) 

Output:

Directory 'C:/Practice' is built!
How to Create a Directory in Python - AskPython (1)

Example 2: Providing permissions for read and write operations within the directory.

import os main_dir = "C:/JournalDev"os.mkdir(main_dir,mode = 0o666) print("Directory '% s' is built!" % main_dir) 

Setting mode = 0o666 allows read and write file operations within the created directory.

Output:

Directory 'C:/JournalDev' is built!
How to Create a Directory in Python - AskPython (2)

Exceptions with os.mkdir() method

The os.mkdir() method raises a FileExistsError Exception if the new directory we want to create already exists in the folder specified.

Example:

Let’s try to create a new directory in the path where the target directory already exists.

import os main_dir = "C:/JournalDev"os.mkdir(main_dir,mode = 0o666) print("Directory '% s' is built!" % main_dir) 

Output:

FileExistsError Traceback (most recent call last)<ipython-input-17-75731447cf21> in <module> 3 main_dir = "C:/JournalDev" 4 ----> 5 os.mkdir(main_dir,mode = 0o666) 6 print("Directory '% s' is built!" % main_dir) 7 FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:/JournalDev'

Here the mkdir() method throws an error as the directory already exists.

Using os.makedirs() method to Create a Directory in Python

The problem with the mkdir() method is that it must that the parent directories mentioned in the path are already present, if not it will raise an error “FileNotFoundError”. There can be many cases where we strictly need to create a directory on the specific path and if any of the parent directories are not present we want it to automatically gets created. Here comes the makedirs() method.

The makedirs() method can create all the intermediate directories as well as the leaf directories if they don’t exist in the specified path.

Syntax:

os.makedirs(path,mode)
  • path: The location wherein the user wants the directory to be created. It is a string or byte value that includes the entire path and name of the directory to be built.
  • mode: The permissions that must be given to deal with the file operations within the directory. The default value is ‘0o777‘.

Example:

import os main_dir = "C:/Examples/Python_files/OS_module"os.makedirs(main_dir,mode = 0o666) print("Directory '% s' is built!" % main_dir) 

In the above example, the makedirs() method creates the intermediate directories ‘Python_files’ as well as the leaf directory ‘OS_module’ in one shot through the method.

Output:

Directory 'C:/Examples/Python_files/OS_module' is built!
How to Create a Directory in Python - AskPython (3)
How to Create a Directory in Python - AskPython (4)
How to Create a Directory in Python - AskPython (5)

Conclusion

In this tutorial, we have seen mkdir() method where a directory will be created if all parent directories specified in the path is present, otherwise, we have another method makedirs() which can create all intermediate-level directory automatically, both method can used in a Python program using OS module. OS module is a built-in module, we just have to write an import statement for using its methods. We hope this tutorial helped you to learn how to create new directories in Python.

Reference

https://docs.python.org/3/library/os.html

How to Create a Directory in Python - AskPython (2024)

References

Top Articles
California Disaster Nutrition Assistance | Food and Nutrition Service
What You Can and Can't Buy With SNAP Benefits
What to Do For Dog Upset Stomach
Online Reading Resources for Students & Teachers | Raz-Kids
Aadya Bazaar
Craigslist Mexico Cancun
Bloxburg Image Ids
Mustangps.instructure
Craigslistdaytona
The Wicked Lady | Rotten Tomatoes
What Was D-Day Weegy
Best Restaurants Ventnor
Craigslist Pikeville Tn
Craigslist Pets Athens Ohio
Po Box 35691 Canton Oh
Webcentral Cuny
The best TV and film to watch this week - A Very Royal Scandal to Tulsa King
Craigslist In Visalia California
Carson Municipal Code
Strange World Showtimes Near Roxy Stadium 14
Dr Ayad Alsaadi
All Obituaries | Gateway-Forest Lawn Funeral Home | Lake City FL funeral home and cremation Lake City FL funeral home and cremation
What Is The Lineup For Nascar Race Today
Blackboard Login Pjc
4 Methods to Fix “Vortex Mods Cannot Be Deployed” Issue - MiniTool Partition Wizard
Top 20 scariest Roblox games
Dr Seuss Star Bellied Sneetches Pdf
Pokemon Inflamed Red Cheats
Housing Intranet Unt
Salemhex ticket show3
Plasma Donation Racine Wi
Tokioof
What are the 7 Types of Communication with Examples
The Rise of "t33n leaks": Understanding the Impact and Implications - The Digital Weekly
Fastpitch Softball Pitching Tips for Beginners Part 1 | STACK
Miss America Voy Board
Los Amigos Taquería Kalona Menu
Cygenoth
9 oplossingen voor het laptoptouchpad dat niet werkt in Windows - TWCB (NL)
How to Get a Better Signal on Your iPhone or Android Smartphone
Who Is Responsible for Writing Obituaries After Death? | Pottstown Funeral Home & Crematory
Cocorahs South Dakota
National Weather Service Richmond Va
Babykeilani
Ts In Baton Rouge
Caesars Rewards Loyalty Program Review [Previously Total Rewards]
Dying Light Mother's Day Roof
Craigslist Sparta Nj
Turok: Dinosaur Hunter
Shannon Sharpe Pointing Gif
Parks And Rec Fantasy Football Names
Predator revo radial owners
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 6506

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.