How do I check if a directory exists in Python?
-
13A word of warning - the highest rated answer might be susceptible to race conditions. You might want to perform `os.stat` instead, to see if the directory both exists and is a directory at the same moment. – d33tah Feb 11 '14 at 17:09
-
3@d33tah You may have a good point but I don't see a way to use `os.stat` to tell directory from a file. It raises `OSError` when the path is invalid, no matter whether it's file or directory. Also, any code after checking is also susceptible to race conditions. – Tomáš Zato Sep 07 '15 at 14:58
15 Answers
Use os.path.isdir
for directories only:
>>> import os
>>> os.path.isdir('new_folder')
True
Use os.path.exists
for both files and directories:
>>> import os
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False
Alternatively, you can use pathlib
:
>>> from pathlib import Path
>>> Path('new_folder').is_dir()
True
>>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
False

- 24,552
- 19
- 101
- 135

- 278,196
- 72
- 453
- 469
-
4@syedrakib While parentheses can be used to indicate that an object is callable, that's not useful in Python, since even classes are callable. Also, functions are first-class values in Python, and you can use them *without* the parentheses notation, like in `existing = filter(os.path.isdir(['/lib', '/usr/lib', '/usr/local/lib'])` – phihag Mar 30 '13 at 07:38
-
11You can pass functions to other functions, like `map`, but in the general case, you call functions with arguments and parentheses. Also, there is some typo in your example. presumably you mean `filter(os.path.isdir, ['/lib', '/usr/lib', '/usr/local/lib'])`. – hughdbrown Mar 31 '13 at 23:02
-
5Also, there is `os.path.isfile(path)` if you only care about whether it is a file. – Nicholas Feb 16 '18 at 18:00
-
3Be aware that on some platforms these will return false if the file/directory exists, but a read permission error also occurs. – cowlinator Dec 05 '18 at 00:39
-
The examples above are not portable, and would be better if rewritten using os.path.join, or the pathlib stuff recommended below. Something like this: print(os.path.isdir(os.path.join('home', 'el'))) – user2773661 Nov 12 '20 at 18:44
-
@user2773661 Good point. I updated the examples. Note your sample is **not** identical because an absolute path must start with a slash; I answered the original question. I left out explaining the difference between starting with `.` vs `os.getcwd()`, since it is irrelevant for most application. – phihag Nov 12 '20 at 19:47
-
For the `pathlib` option (which I prefer), you can also just use the relative path like `(Path.('new_folder') / 'file.txt').exists()`. To resolve the path to a full qualified (absolute) path, you can use `Path(...).resolve()` – Cadoiz Jul 20 '21 at 15:46
Python 3.4 introduced the pathlib
module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir()
and exists()
methods of a Path
object can be used to answer the question:
In [1]: from pathlib import Path
In [2]: p = Path('/usr')
In [3]: p.exists()
Out[3]: True
In [4]: p.is_dir()
Out[4]: True
Paths (and strings) can be joined together with the /
operator:
In [5]: q = p / 'bin' / 'vim'
In [6]: q
Out[6]: PosixPath('/usr/bin/vim')
In [7]: q.exists()
Out[7]: True
In [8]: q.is_dir()
Out[8]: False
Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.

- 43,590
- 17
- 150
- 159
So close! os.path.isdir
returns True
if you pass in the name of a directory that currently exists. If it doesn't exist or it's not a directory, then it returns False
.

- 30,189
- 5
- 49
- 65
-
-
4Or using pathlib: `Path(path).mkdir(parents=True, exist_ok=True)` creates a nested path in one operation. – Kirk Strauser Jan 03 '22 at 21:20
Yes, use os.path.exists()
.

- 5,838
- 26
- 30
-
27
-
10Good call. Others have pointed out that `os.path.isdir` will accomplish that. – aganders3 Jan 19 '12 at 21:13
-
4If you understand that this doesn't answer the question, why don't you remove the answer? – Jul 13 '16 at 20:42
-
3@CamilStaps This question was viewed 354000 times (by now). Answers here are not only for OP, they are for anyone who could come here for whatever reason. aganders3's answer is pertinent even if it does not directly resolve OP's problem. – Gabriel Oct 14 '16 at 17:54
-
6
-
To be fair, the statement “find if a directory exists” tends to exclude the non-directory case by implication: we have a “notional directory” that either exists or doesn’t. That doesn’t make this a particularly *useful* way of thinking about the problem. – Davis Herring Oct 14 '19 at 01:45
We can check with 2 built in functions
os.path.isdir("directory")
It will give boolean true the specified directory is available.
os.path.exists("directoryorfile")
It will give boolead true if specified directory or file is available.
To check whether the path is directory;
os.path.isdir("directorypath")
will give boolean true if the path is directory

- 4,446
- 2
- 39
- 46
The following code checks the referred directory in your code exists or not, if it doesn't exist in your workplace then, it creates one:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")

- 845
- 1
- 9
- 23
You may also want to create the directory if it's not there.
Source, if it's still there on SO.
=====================================================================
On Python ≥ 3.5, use pathlib.Path.mkdir
:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:
Try os.path.exists
, and consider os.makedirs
for the creation.
import os
if not os.path.exists(directory):
os.makedirs(directory)
As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists
and the os.makedirs
calls, the os.makedirs
will fail with an OSError
. Unfortunately, blanket-catching OSError
and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.
One option would be to trap the OSError
and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):
import os, errno
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
Alternatively, there could be a second os.path.exists
, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.
Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
Modern versions of Python improve this code quite a bit, both by exposing FileExistsError
(in 3.3+)...
try:
os.makedirs("path/to/directory")
except FileExistsError:
# directory already exists
pass
...and by allowing a keyword argument to os.makedirs
called exist_ok
(in 3.2+).
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.

- 950
- 2
- 11
- 31
As in:
In [3]: os.path.exists('/d/temp')
Out[3]: True
Probably toss in a os.path.isdir(...)
to be sure.

- 14,697
- 4
- 41
- 54
Just to provide the os.stat
version (python 2):
import os, stat, errno
def CheckIsDir(directory):
try:
return stat.S_ISDIR(os.stat(directory).st_mode)
except OSError, e:
if e.errno == errno.ENOENT:
return False
raise

- 3,048
- 1
- 23
- 27
-
What is the advantage to use `stat` and `errno` instead of [pathlib2](https://pypi.python.org/pypi/pathlib2/)? Is it the race conditions mentioned in [d33tah](https://stackoverflow.com/users/1091116/d33tah)'s comment to the question? – Cadoiz Jul 20 '21 at 15:51
os provides you with a lot of these capabilities:
import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in) #gets you a list of all files and directories under dir_in
the listdir will throw an exception if the input path is invalid.

- 146,994
- 96
- 417
- 335

- 109
- 1
- 3
#You can also check it get help for you
if not os.path.isdir('mydir'):
print('new directry has been created')
os.system('mkdir mydir')

- 654
- 9
- 11
-
8python has builtin functions to create directories, so better use `os.makedirs('mydir')` instead of `os.system(...)` – gizzmole Jan 11 '18 at 13:05
-
9You are printing that *'new directory has been created'* but you do not know that. What if you do not have permissions to create a directory? You would print *'new directory has been created'* but it would not be true. Would it. – Wojciech Jakubas Feb 27 '18 at 15:22
There is a convenient Unipath
module.
>>> from unipath import Path
>>>
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True
Other related things you might need:
>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True
You can install it using pip:
$ pip3 install unipath
It's similar to the built-in pathlib
. The difference is that it treats every path as a string (Path
is a subclass of the str
), so if some function expects a string, you can easily pass it a Path
object without a need to convert it to a string.
For example, this works great with Django and settings.py
:
# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'

- 12,464
- 7
- 65
- 73

- 29,384
- 19
- 111
- 115
Two things
- check if the directory exist?
- if not, create a directory (optional).
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.
if os.path.exists(dirpath):
print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
os.mkdir(dirpath):
print("Directory created")

- 659
- 8
- 8
-
If you're going to do this then why not just os.mkdir() and catch (and ignore) FileExistsError. Your example has a time-of-check/time-of-use race. There is a non-zero delay between checking that dirpath exists and then taking action if it doesn't. In that time someone else could potentially make an object at dirpath and you'd have to deal with the exception anyway. – Adam Hawes Aug 07 '20 at 04:35
-
@AdamHawes, the solution is based on the query that was asked, the query specifically ask about "find if a directory exists", once the ` if os.path.exists ` is validated, it is up to the coder to decide on further proceedings, ` os.mkdir ` is only an assumptive action, hence I mentioned it as an option in the code. – Uday Kiran Oct 25 '20 at 04:15
Step 1: Import the os.path module
import the os.path module before running the code.
import os.path
from os import path
Step 2: Use path.exists() function
The path.exists() method is used to find whether a file exists.
path.exists("your_file.txt")
Step 3: Use os.path.isfile()
We can use the isfile command to determine whether or not a given input is a file.
path.isfile('your_file.txt')
step 4: Use os.path.isdir()
We can use the os.path.dir() function to determine whether or not a given input is a directory.
path.isdir('myDirectory')
Here is the complete code
import os.path
from os import path
def main():
print ("File exists:"+str(path.exists('your_file.txt')))
print ("Directory exists:" + str(path.exists('myDirectory')))
print("Item is a file: " + str(path.isfile("your_file.txt")))
print("Item is a directory: " + str(path.isdir("myDirectory")))
if __name__== "__main__":
main()
pathlibPath.exists() For Python 3.4
Pathlib Module is included in Python 3.4 and later versions to handle file system paths. Python checks if a folder exists using an object-oriented technique.
import pathlib
file = pathlib.Path("your_file.txt")
if file.exists ():
print ("File exist")
else:
print ("File not exist")
- os.path.exists() – Returns True if path or directory does exists.
- os.path.isfile() – Returns True if path is File.
- os.path.isdir() – Returns True if path is Directory.
- pathlib.Path.exists() – Returns True if path or directory does exists. (In Python 3.4 and above versions)
Article refered How do I check if directory exists in Python?

- 154
- 8