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
You're looking for os.path.isdir
, or os.path.exists
if you don't care whether it's a file or a directory:
>>> import os
>>> os.path.isdir('new_folder')
True
>>> 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
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.
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
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.
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'
Two things
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")
os.stat
instead, to see if the directory both exists and is a directory at the same moment. – d33tahos.stat
to tell directory from a file. It raisesOSError
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 - Reinstate Monica