+

Python | os.path.isdir () method

The OS module in Python provides functions for interacting with the operating system. The operating system is covered by standard Python utility modules. This module provides a portable way to use operating system-dependent functions. The os.path module is a slave of the OS module in Python used to manipulate common path names.

Syntax: os.path.isdir(path)

Parameter:
path: A path-like object representing a file system path.

Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing directory, otherwise returns False.



The os.path.isdir () method in Python checks whether the given path is an existing directory or not. This method follows a symbolic link, which means that if the specified path is a symbolic link pointing to a directory, the method returns True.

OS Path isDir

os.path.isdir(path)

Return True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.

Pros and Cons between os path exists vs os path isdir

Stackoverflow question

I'm checking to see if a directory exists, but I noticed I'm using os.path.exists instead of os.path.isdir. Both work just fine, but I'm curious as to what the advantages are for using isdir instead of exists.

Answer

os.path.exists will also return True if there's a regular file with that name.

os.path.isdir will only return True if that path exists and is a directory, or a symbolic link to a directory.

Example #1

def find_package_dirs(root_path):
    """ Find python package directories in directory `root_path`

    Parameters
    ----------
    root_path : str
        Directory to search for package subdirectories

    Returns
    -------
    package_sdirs : set
        Set of strings where each is a subdirectory of `root_path`, containing
        an ``__init__.py`` file.  Paths prefixed by `root_path`
    """
    package_sdirs = set()
    for entry in os.listdir(root_path):
        fname = entry if root_path == '.' else pjoin(root_path, entry)
        if isdir(fname) and exists(pjoin(fname, '__init__.py')):
            package_sdirs.add(fname)
    return package_sdirs 

Example #2

def compile_bundle_entry(self, spec, entry):
        """
        Handler for each entry for the bundle method of the compile
        process.  This copies the source file or directory into the
        build directory.
        """

        modname, source, target, modpath = entry
        bundled_modpath = {modname: modpath}
        bundled_target = {modname: target}
        export_module_name = []
        if isfile(source):
            export_module_name.append(modname)
            copy_target = join(spec[BUILD_DIR], target)
            if not exists(dirname(copy_target)):
                makedirs(dirname(copy_target))
            shutil.copy(source, copy_target)
        elif isdir(source):
            copy_target = join(spec[BUILD_DIR], modname)
            shutil.copytree(source, copy_target)

        return bundled_modpath, bundled_target, export_module_name 

Example #3

def cache_asset(cache_dir, cache_f, path, asset_id):
    r"""
    Caches the info for a given asset id so it can be efficiently
    served in the future.

    Parameters
    ----------
    asset_id : `str`
    The id of the asset that needs to be cached
    """
    asset_cache_dir = p.join(cache_dir, asset_id)
    if not p.isdir(asset_cache_dir):
        os.mkdir(asset_cache_dir)
    cache_f(cache_dir, path, asset_id)


# IMAGE CACHING 

Example #4

def find_node_modules_basedir(self):
        """
        Find all node_modules directories configured to be accessible
        through this driver instance.

        This is typically used for adding the direct instance, and does
        not traverse the parent directories like what Node.js does.

        Returns a list of directories that contain a 'node_modules'
        directory.
        """

        paths = []

        # First do the working dir.
        local_node_path = self.join_cwd(NODE_MODULES)
        if isdir(local_node_path):
            paths.append(local_node_path)

        # do the NODE_PATH environment variable last, as Node.js seem to
        # have these resolving just before the global.
        if self.node_path:
            paths.extend(self.node_path.split(pathsep))

        return paths 

Example #5

def find_system_jdks():
    """
    Returns a set of valid JDK directories by searching standard locations.
    """
    bases = [
        '/Library/Java/JavaVirtualMachines',
        '/usr/lib/jvm',
        '/usr/java',
        '/usr/jdk/instances',
        r'C:\Program Files\Java'
    ]
    jdks = set()
    for base in bases:
        if isdir(base):
            for n in os.listdir(base):
                jdk = join(base, n)
                mac_jdk = join(jdk, 'Contents', 'Home')
                if isdir(mac_jdk):
                    jdk = mac_jdk
                if is_valid_jdk(jdk):
                    jdks.add(realpath(jdk))
    return jdks 


Archived version

os.path.isdir() in Python is used to check if the specified path is an existing directory or not. This method follows a symbolic link, which means that if the specified path is a symbolic link pointing to a directory, then the method will return True.

Syntax: os.path.isdir (path)

Parameter:
path : A path- like object representing a file system path.

Return Type: This method returns a Boolean value of class bool . This method returns True if specified path is an existing directory, otherwise returns False.

Code # 1: Using method os.path.isdir()

# Python program to explain the os.path.isdir () method

 
# import of the os.path module

import os.path

 
# Path

path = `/ home / User / Documents / file.txt`

 
# Check
# the specified path is
# existing directory or not

isdir = os.path.isdir (path)

print (isdir)

 

 
# Path

path = `/ home / User / Documents /`

 
# Check
# specified path is
# existing directory or not

isdir = os.path.isdir (path)

print (isdir)

Exit :

 False True 

Code # 2: if the specified path is a symbolic link

# Python program to explain the os method .path.isdir ()

 
# import of the os.path module

import os.path

 

  
# Create directory
# (in the current working directory)

dirname = "GeeksForGeeks"

os.mkdir (dirname)

 
# Create a symbolic link
# points to the above directory

symlink_path = " / home / User / Desktop / gfg "

os.symlink (dirname, symlink_path)

 

 

path = dirname

 
# Now check,
# the specified path is
# existing directory or not

isdir = os.path.isdir (path)

print (isdir)

 

path = symlink_path

 
# Check
# the specified path (which is
# symlink) is
# existing directory or not

isdir = os.path.isdir (path)

print (isdir)

Exit :

 True True  

Link: https://docs.python .org / 3 / library / os.path.html

Get Solution for free from DataCamp guru