AppDividend
Latest Code Tutorials

How To Create Directory In Python With Example

1

Python os.mkdir() is an inbuilt function that creates a directory. The OS module in Python gives methods for interacting with the operating system. The OS module comes under Python’s standard utility modules. The OS module provides the portable way of using operating system dependent functionality.

Python create directory

Reading and writing files do not require loading the additional module, but accessing a file system functions requires that we use the separate module.

First, the os module has to be imported. The os is a Python module that belongs to a core part of the Python ecosystem. It is done using the import statement as follows.

import os

There are two main methods available in the OS module for creating a directory. These are the following.

  1. os.mkdir()
  2. os.makedirs()

Python os.mkdir()

Python’s OS module provides the function to create the directory. The os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raises FileExistsError if the directory to be created already exists.

Syntax

os.mkdir(path, mode = 0o777, *, file_descriptor = None)

Parameters

path: It takes a path as a required parameter, which is the path to which we want to create a directory. A path-like object is representing the file system path. A path-like object is either the string or bytes object representing a path.

mode (optional): It is an Integer value representing a mode of a directory to be created. If the mode parameter is omitted, then default value 777 is used.

file_descriptor(optional): A file descriptor referring to a directory. The default value of this parameter is None. If the specified path is absolute, then file_descriptor is ignored.

Example

See the following code.

import os

dir = 'app'
try:
    os.mkdir(dir)
    print("Directory ", dir,  "is Created ")
except FileExistsError:
    print("Directory ", dir,  " already exists")

Output

python3 app.py
Directory  app  already exists

When you run the first time, it will give us the above output. Now, you can see that the app directory is created in your current project folder.

Now, run the above file second time and see the output.

python3 app.py
Directory  app  already exists

That means it gives us FileExistsError, which means that the folder already exists.

Python not operator

To check an existing folder in a particular directory, we can use Python, not operator with Python os.path.exists() function. See the following code.

# app.py

import os

dir = 'routes'
if not os.path.exists(dir):
    os.mkdir(dir)
    print("Directory ", dir,  "is Created ")
else:
    print("Directory ", dir,  " already exists")

Output

python3 app.py
Directory  routes is Created

Now, again if you run the file, then it compiler finds that the folder already exists so it will execute the else condition.

The os.mkdir(path) will create the given directory only, but it will not create the intermediate directory in the given path.

So let’s say if we want to create a directory inside the directory, and both directories do not exist, then it won’t create any directory.

For example, if we want to create a >> b >> c in which we are at the a folder, and now we want to create and folder, then it is not possible. At max, it will create a folder and not after c.

See the following code.

# app.py

import os

dir = 'a/b/c'

os.mkdir(dir)

Output

python3 app.py
Traceback (most recent call last):
  File "app.py", line 5, in <module>
    os.mkdir(dir)
FileNotFoundError: [Errno 2] No such file or directory: 'a/b/c'

Here compiler does not create any directory and returns an error because it tries to find ‘a/b/c’ directory and not a >> b >> c directory. It takes a path as a whole string, and that is why it won’t create.

The os.mkdir(path) can not create intermediate directories in the given path if they are not present. It will throw the error in such cases. For that, we need another function.

Python os.makedirs()

Python os.makedirs() is an inbuilt method that is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, osmakedirs() method will create them all.

Syntax

os.makedirs(path)

The os.makedirs(name) will create the directory on a given path, and also, if any intermediate-level directory doesn’t exist, then it will create that too.

Let’s create a directory with intermediate directories with the following code.

# app.py

import os

dir = 'a/b/c'
try:
    os.makedirs(dir)    
    print("Directory " , dir ,  " Created ")
except FileExistsError:
    print("Directory " , dir ,  " already exists")  

Output

python3 app.py
Directory  a/b/c is Created

Now, if there are no directories like a >> b >> c, then the above code will create one for you.

See also

How to read file in Python

How to write file in Python

How to list files in Python

1 Comment
  1. sd says

    thanks

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.