Advertisement
Advertisement


How to find if directory exists in Python


Question

In the os module in Python, is there a way to find if a directory exists, something like:

>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
2015/12/14
1
1166
12/14/2015 6:45:29 PM

Accepted Answer

You're looking for os.path.isdir, or os.path.exists if you don't care whether it's a file or a directory.

Example:

import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))
2015/02/26
1764
2/26/2015 1:32:41 PM

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.

2012/01/19

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.

2020/01/25

Yes, use os.path.exists().

2012/01/19

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

2018/03/26

2012/01/19

Source: https://stackoverflow.com/questions/8933237
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]