Categories
Python Answers

How to check if a directory exists in Python?

Spread the love

Sometimes, we want to check if a directory exists in Python.

In this article, we’ll look at how to check if a directory exists in Python.

How to check if a directory exists in Python?

To check if a directory exists in Python, we can use the os.path.isdir or os.path.exists methods.

For instance, we write:

import os

isdir = os.path.isdir('new_folder')
print(isdir)

We pass in the path string to check if whether the directory with the given path exists.

isdir is True if the folder exists at the given path. Otherwise, it’s False.

To use os.path.exists, we write:

import os

isdir = os.path.exists(os.path.join(os.getcwd(), 'new_folder'))
print(isdir)

We call os.path.exists with the path created with os.path.join that joins the path segments together.

os.getcwd() returns the path of the current working directory.

isdir is True if the folder exists at the given path. Otherwise, it’s False.

Conclusion

To check if a directory exists in Python, we can use the os.path.isdir or os.path.exists methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.