How to make a folder directory in Python?

In this short Python automation tutorial, we’ll learn to create a new directory if it still doesn’t exists in your file system using the Python language. We’ll provide examples using the pathlib (available from Python 3.4) and the os libraries; both parts of the Python standard library. The examples below work in both Windows, macOS and Linux operating systems.

Check that a directory exists with pathlib and os

You can use the pathlib Path is_dir() method to check that a folder exists:

from pathlib import Path

dir_path = Path("C:\Work_Dir")
if dir_path.is_dir():
    print('Directory already exists')
else:
    print('Directory doesn\'t exist')

With os:

import os
if os.path.isdir(dir_path):
    print('Directory already exists')
else:
    os.mkdir(dir_path)
    print('Directory doesn\'t exist')

Make a directory in Python

We will first whether the file system has a directory with the same path, if not we’ll create a new folder.

With pathlib:

from pathlib import Path

dir_path = Path("C:\Work_Dir")
if dir_path.is_dir():
    print('Directory already exists')
else:
    #create the folder    
    dir_path.mkdir()
    print('Directory created at: {}'.format(dir_path))

Wth the os module:

import os
if os.path.isdir(dir_path):
    print('Directory already exists')
else:
    os.mkdir(dir_path)
    print('Directory created at: {}'.format(dir_path))

Remember: Don’t forget to import pathlib and / or os modules before using them in your program. Failing to do that will render the following name error:

NameError: name 'os' is not defined

Get the current directory name

If you need the current directory information you can find it using the follow snippets:


#pathlib
Path.cwd()

#os
os.getcwd()

Saving a new file into the new directory

You can easily create new files into the new folder:

from pathlib import Path
file_name = "new_file.txt"
file_path = dir_path.joinpath(file_name)
if dir_path.is_dir():
    with open(file_path, "w") as myfile:
        myfile.write("THis is a new file that we added into the file system.")

Follow up learning

How to save an array into a csv file with Python?