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)

FAQs

How to create a new 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 you create a working directory in Python? ›

You can use the os. mkdir("path/to/dir/here") function to create a directory in Python. This function is helpful if you need to create a new directory that doesn't already exist. However, as you have learned above, this function will only work across operating systems, if you construct the path with os.

How to add a file directory in Python? ›

Adding Python files
  1. In the Workspace tool window ( Alt 01 ), select the directory in which you want to create a new file, and then choose File | New from the main menu.
  2. Right-click the directory and select New from the context menu.
  3. Select the directory and press Alt Insert .
May 26, 2024

How to create a directory in Python if it doesn't exist? ›

Python Make Directory If Not Exists Using os. path. exists() and os. makedirs() Methods
  1. Step 1: Import the os Module. To begin, we need to import the os module in our Python script. ...
  2. Step 2: Specify the Directory Path. ...
  3. Step 3: Check if the Directory Exists.
Apr 1, 2024

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.

How to create a directory in Jupyter notebook? ›

To create a new directory using the Jupyter Notebook dashboard, you can click on the drop-down menu labeled New , and then select Folder . You can create new directories in the Jupyter dashboard by clicking on New and then selecting Folder from the drop-down menu. Note that new directories are created as Untitled.

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 to get 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 to create a path in Python? ›

Example 1: Create A File Path With Variables Using String Concatenation. In the provided code, a file path is constructed by concatenating a base path (“/path/to”) and a file name (“example. txt”). The resulting file path is then used to create and open a new text file in write mode.

How to list a directory in Python? ›

How to List Files in a Python Directory
  1. Use os. listdir() to print all files.
  2. Use os. walk() to access files deeper into a decision tree.
  3. Use the glob module to search by regular expression.
  4. Use the pathlib module to generate all path file names.
  5. Use the os. scandir() function to return a generator.

How to make a directory in terminal? ›

Use the mkdir command to create one or more directories specified by the Directory parameter. Each new directory contains the standard entries dot (.) and dot dot (..). You can specify the permissions for the new directories with the -m Mode flag.

How to create new files in Python? ›

Create a New Text File Using open() Function

txt . The file is opened in write mode, and the specified content is written into it. Finally, a success message is printed, confirming the successful creation of the file.

How to make a directory using Python? ›

Method 1: Using os. mkdir() Method to Create a Directory in Python
  1. OS module has an in-built method os mkdir() to create directories using Python in the system.
  2. In the above example, we are passing the path string that has the location followed by name of the new directory that we need to create.
Jan 30, 2024

How do I create an empty 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 create a directory in Python idle? ›

mkdir() method to create a new single directory. The os. mkdir() method accepts one argument – the path for the directory. The code above will create a projects directory in the current working directory.

How do I create a new directory in repository? ›

To create a new folder in Github, you can navigate to the desired repository, then: Click on the "Add file" button followed by the "Create new file" link in the dropdown menu.

What is the Python equivalent of mkdir? ›

The os. makedirs() method is used to create a directory recursively in the os module using Python. It is similar to the method os. mkdir() with the addition that it also creates intermediate directories to create leaf directories.

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.

Top Articles
Ā ā | How to Type A Macron Sign [A with Line Over It] (On Keyboard) - Software Accountant
7 Gipfeltouren im Nürnberger Land
Hsqa Online Renewal System
scotty rasmussen paternity court
C Chord for Ukulele: Variations, Styles, and Techniques
Recruitment Drive/Quick guide
15 Cloud Tattoo Meaning Symbolism- Reflecting Change and Transience
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Things to do in Wichita Falls on weekends 12-15 September
On Trigger Enter Unity
9:00 A.m. Cdt
Uwa Schedule
Craigslist Tuscarawas Pets
8 Restaurant-Style Dumpling Dipping Sauces You Can Recreate At Home
Giantesssave
Kate Spade OUTLET • bis 70%* im Sale | Outletcity Metzingen
Crazy 8S Cool Math
Staples Ups Drop Off
Christopher Goosley Obituary
How Much Does Costco Gas Cost Today? Snapshot of Prices Across the U.S. | CostContessa
Clarkson Eyecare hiring Optometrist - Fredericksburg, VA in Fredericksburg, VA | LinkedIn
Taco Bell Fourth Of July Hours
Melanin - Altmeyers Enzyklopädie - Fachbereich Dermatologie
Craigslist Eugene Motorcycles
Mega Millions Lottery - Winning Numbers & Results
I Wanna Dance With Somebody Showtimes Near St. Landry Cinema
Gran Turismo Showtimes Near Epic Theatres Of Ocala
Peloton Guide Stuck Installing Update
Provo Craigslist
Look Who Got Busted New Braunfels
Bryant Air Conditioner Parts Diagram
Jasminx Fansly
Ucf Net Price Calculator
Odawa Hypixel
Texas Motors Specialty Photos
Seats 3D Ubs Arena
Middletown Pa Craigslist
Az610 Flight Status
Lockstraps Net Worth
Super Bowl 17 Ray Finkle
Flowers Jewel Osco
Thotsbay New Site
Craigslist Cars Merced Ca
Pre-Order Apple Watch Series 10 – Best Prices in Dubai, UAE
158 Rosemont Ringoes Rd, East Amwell Twp, NJ, 08559 | MLS #3921765 | RocketHomes
Tses Orts.com
Dontrell Williams Miami First 48
Katopunk Pegging
Stroom- of gasstoring? | Stedin
What Time Does The Chase Bank Close On Saturday
Pasha Pozdnyakova
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 6404

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.