Python | os.path.realpath () method

The Python OS module provides functions for interacting with the operating system. The OS comes with standard Python service modules. This module provides a portable way to use operating system specific functionality. The os.path module is a submodule of the Python OS module that is used to manage shared paths. os.path.realpath () in Python is used to get the canonical path of the specified filename by removing any symbolic links that occur in the path.
Syntax: os.path.realpath(path)

path: A path-like object representing the file system path.
A path-like object is either a string or bytes object representing a path.

Return Type: This method returns a string value which represents the canonical path.

Create soft link or symbolic link

On Unix or Linux, a soft link or symbolic link can be created using the ln command. Following is the syntax for creating a symbolic link on the command line:
$ ln -s {source-filename} {symbolic-filename}

Example 1

def realpath(self, spec, key):
        Resolve and update the path key in the spec with its realpath,
        based on the working directory.

        if key not in spec:
            # do nothing for now

        if not spec[key]:
                "cannot resolve realpath of '%s' as it is not defined", key)

        check = realpath(join(spec.get(WORKING_DIR, ''), spec[key]))
        if check != spec[key]:
            spec[key] = check
                "realpath of '%s' resolved to '%s', spec is updated",
                key, check
        return check

    # Setup related methods 

Example 2

def get_rp_stripper(strip_path):
    """ Return function to strip ``realpath`` of `strip_path` from string

    strip_path : str
        path to strip from beginning of strings. Processed to ``strip_prefix``
        by ``realpath(strip_path) + os.path.sep``.

    stripper : func
        function such that ``stripper(a_string)`` will strip ``strip_prefix``
        from ``a_string`` if present, otherwise pass ``a_string`` unmodified
    return get_prefix_stripper(realpath(strip_path) + os.path.sep) 

Example 3

def test_toolchain_standard_not_implemented(self):
        spec = Spec()

        with self.assertRaises(NotImplementedError):

        with self.assertRaises(NotImplementedError):

        with self.assertRaises(NotImplementedError):

        # Check that the build_dir is set on the spec based on tempfile
        # Also that it got deleted properly.

Example 4

def find_system_jdks():
    Returns a set of valid JDK directories by searching standard locations.
    bases = [
        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):
    return jdks 

Example 5

def _expand_dirs_to_files(files_or_dirs, recursive=False):
    files = []
    files_or_dirs = _ensure_list(files_or_dirs)
    for file_or_dir in files_or_dirs:
        file_or_dir = op.realpath(file_or_dir)
        if op.isdir(file_or_dir):
            # Skip dirnames starting with '.'
            if _to_skip(file_or_dir):
            # Recursively visit the directories and add the files.
            if recursive:
                files.extend(_expand_dirs_to_files([op.join(file_or_dir, file)
                             for file in os.listdir(file_or_dir)],
                files.extend([op.join(file_or_dir, file)
                              for file in os.listdir(file_or_dir)])
        elif '*' in file_or_dir:
    return files 

Example 6

def getSubdirs(path, baseNamesOnly=True, excludePythonModulesDirs=True):
    """Provides a list of sub directories for the given path"""
    subdirs = []
        path = realpath(path) + sep
        for item in os.listdir(path):
            candidate = path + item
            if isdir(candidate):
                if excludePythonModulesDirs:
                    modFile = candidate + sep + "__init__.py"
                    if exists(modFile):
                if baseNamesOnly:
    return subdirs 

Example 7

def get_dataset(num_points):
    name = 'ModelNet10'
    path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name)
    pre_transform = T.NormalizeScale()
    transform = T.SamplePoints(num_points)

    train_dataset = ModelNet(
    test_dataset = ModelNet(

    return train_dataset, test_dataset 

Example 8

def getParameters(self):
        """Provides a dictionary with the search parameters"""
        parameters = {'term': self.findCombo.currentText(),
                      'case': self.caseCheckBox.isChecked(),
                      'whole': self.wordCheckBox.isChecked(),
                      'regexp': self.regexpCheckBox.isChecked()}
        if self.projectRButton.isChecked():
            parameters['in-project'] = True
            parameters['in-opened'] = False
            parameters['in-dir'] = ''
        elif self.openFilesRButton.isChecked():
            parameters['in-project'] = False
            parameters['in-opened'] = True
            parameters['in-dir'] = ''
            parameters['in-project'] = False
            parameters['in-opened'] = False
            parameters['in-dir'] = realpath(
        parameters['file-filter'] = self.filterCombo.currentText().strip()

        return parameters 

Example 9

def _check_if_pyc(fname):
    """Return True if the extension is .pyc, False if .py
    and None if otherwise"""
    from imp import find_module
    from os.path import realpath, dirname, basename, splitext

    # Normalize the file-path for the find_module()
    filepath = realpath(fname)
    dirpath = dirname(filepath)
    module_name = splitext(basename(filepath))[0]

    # Validate and fetch
        fileobj, fullpath, (_, _, pytype) = find_module(module_name, [dirpath])
    except ImportError:
        raise IOError("Cannot find config file. "
                      "Path maybe incorrect! : {0}".format(filepath))
    return pytype, fileobj, fullpath 

Example 10

def get_planetoid_dataset(name, normalize_features=False, transform=None):
    path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name)
    dataset = Planetoid(path, name)

    if transform is not None and normalize_features:
        dataset.transform = T.Compose([T.NormalizeFeatures(), transform])
    elif normalize_features:
        dataset.transform = T.NormalizeFeatures()
    elif transform is not None:
        dataset.transform = transform

    return dataset 

Example 11

def _setup_logger(cls, log_file=None):
        formatter = logging.Formatter(
            fmt="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
        screen_handler = logging.StreamHandler(stream=sys.stdout)
        logger = logging.getLogger(cls.__name__)

        if log_file:
            file_handler = logging.FileHandler(realpath(log_file), mode="w")

        return logger 

Example 12

def bro_server(bro_file, interface="eth0", bro_path="/usr/local/bro/bin/bro"):
    u""" 跑bro服务进程 """
    # 获取绝对路径
    bro_file = path.realpath(bro_file)
    http_file = "/usr/local/bro/share/bro/base/protocols/http/main.bro"
    bro_scripts = ' '.join([bro_file, http_file])

    cmd = "sudo {bro_path} -C -b -i {interface} {bro_scripts}"
    cmd = cmd.format(bro_path=bro_path,

    msg = "the cmd is: %s" % cmd

    # change pwd to /tmp
    tmp_dir = path.join(path.dirname(path.realpath(__file__)), '../../tmp/')

    result = run(cmd)

Example 13

def ProcessFlags(env, flags):
    for f in flags:
        if f:

    # fix relative CPPPATH
    for i, p in enumerate(env.get("CPPPATH", [])):
        if isdir(p):
            env['CPPPATH'][i] = realpath(p)

    # Cancel any previous definition of name, either built in or
    # provided with a -D option // Issue #191
    undefines = [u for u in env.get("CCFLAGS", []) if u.startswith("-U")]
    if undefines:
        for undef in undefines:
        env.Append(_CPPDEFFLAGS=" %s" % " ".join(undefines)) 

Example 14

def _get_settings_helper(self):
        main_dir = path.dirname(path.realpath(__file__))
        main_dir = path.realpath(path.join(main_dir, '..', '..'))
        default_filepath = path.join(main_dir, 'default_settings.yml')
        user_filepath = path.join(main_dir, 'settings.yml')
        args = self._get_args()
        if args.settings_path:
            user_filepath = args.settings_path

        # open the default file and get version information
        with open(default_filepath) as default_filestream:
            default_filesettings = yaml.load(default_filestream)

        # FIXME: not used
        current_version = default_filesettings['version'].split('.') # flake8: noqa

        if path.exists(user_filepath):
            filepath = user_filepath
            filepath = default_filepath

        with open(filepath) as setting_file:
            self.settings = yaml.load(setting_file, _OrderedLoader)

        return SpecialDict(**self.settings) 

Example 15

def resolve_rpath(lib_path, rpaths):
    """ Return `lib_path` with its `@rpath` resolved

    If the `lib_path` doesn't have `@rpath` then it's returned as is.

    If `lib_path` has `@rpath` then returns the first `rpaths`/`lib_path`
    combination found.  If the library can't be found in `rpaths` then a
    detailed warning is printed and `lib_path` is returned as is.

    lib_path : str
        The path to a library file, which may or may not start with `@rpath`.
    rpaths : sequence of str
        A sequence of search paths, usually gotten from a call to `get_rpaths`.

    lib_path : str
        A str with the resolved libraries realpath.
    if not lib_path.startswith('@rpath/'):
        return lib_path

    lib_rpath = lib_path.split('/', 1)[1]
    for rpath in rpaths:
        rpath_lib = realpath(pjoin(rpath, lib_rpath))
        if os.path.exists(rpath_lib):
            return rpath_lib

        "Couldn't find {0} on paths:\n\t{1}".format(
            '\n\t'.join(realpath(path) for path in rpaths),
    return lib_path 

Example 16

def wheel_libs(wheel_fname, filt_func=None):
    """ Return analysis of library dependencies with a Python wheel

    Use this routine for a dump of the dependency tree.

    wheel_fname : str
        Filename of wheel
    filt_func : None or callable, optional
        If None, inspect all files for library dependencies. If callable,
        accepts filename as argument, returns True if we should inspect the
        file, False otherwise.

    lib_dict : dict
        dictionary with (key, value) pairs of (``libpath``,
        ``dependings_dict``).  ``libpath`` is library being depended on,
        relative to wheel root path if within wheel tree.  ``dependings_dict``
        is (key, value) of (``depending_lib_path``, ``install_name``).  Again,
        ``depending_lib_path`` is library relative to wheel root path, if
        within wheel tree.
    with TemporaryDirectory() as tmpdir:
        zip2dir(wheel_fname, tmpdir)
        lib_dict = tree_libs(tmpdir, filt_func)
    return stripped_lib_dict(lib_dict, realpath(tmpdir) + os.path.sep)

Example 17

def main():
    parser = OptionParser(
        usage="%s WHEEL_OR_PATH_TO_ANALYZE\n\n" % sys.argv[0] + __doc__,
        version="%prog " + __version__)
        Option("-a", "--all",
               help="Show all dependencies, including system libs"),
        Option("-d", "--depending",
               help="Show libraries depending on dependencies")])
    (opts, paths) = parser.parse_args()
    if len(paths) < 1:

    multi = len(paths) > 1
    for path in paths:
        if multi:
            print(path + ':')
            indent = '   '
            indent = ''
        if isdir(path):
            lib_dict = tree_libs(path)
            lib_dict = stripped_lib_dict(lib_dict, realpath(getcwd()) + psep)
            lib_dict = wheel_libs(path)
        keys = sorted(lib_dict)
        if not opts.all:
            keys = [key for key in keys if filter_system_libs(key)]
        if not opts.depending:
            if len(keys):
                print(indent + ('\n' + indent).join(keys))
        i2 = indent + '    '
        for key in keys:
            print(indent + key + ':')
            libs = lib_dict[key]
            if len(libs):
                print(i2 + ('\n' + i2).join(libs)) 

Example 18

def test_given_directory():
    # Test InGivenDirectory
    cwd = getcwd()
    with InGivenDirectory() as tmpdir:
        assert_equal(tmpdir, abspath(cwd))
        assert_equal(tmpdir, abspath(getcwd()))
    with InGivenDirectory(MY_DIR) as tmpdir:
        assert_equal(tmpdir, MY_DIR)
        assert_equal(realpath(MY_DIR), realpath(abspath(getcwd())))
    # We were deleting the Given directory!  Check not so now.

Example 19

def decideClean(workDir, architecture, aggressiveCleanup):
  """ Decides what to delete, without actually doing it:
      - Find all the symlinks in "BUILD"
      - Find all the directories in "BUILD"
      - Schedule a directory for deletion if it does not have a symlink
  symlinksBuild = [os.readlink(x) for x in glob.glob("%s/BUILD/*-latest*" % workDir)]
  # $WORK_DIR/TMP should always be cleaned up. This does not happen only
  # in the case we run out of space while unpacking.
  # $WORK_DIR//store can be cleaned up as well, because
  # we do not need the actual tarballs after they have been built.
  toDelete = ["%s/TMP" % workDir]
  if aggressiveCleanup:
    toDelete += ["%s/TARS/%s/store" % (workDir, architecture),
                 "%s/SOURCES" % (workDir)]
  allBuildStuff = glob.glob("%s/BUILD/*" % workDir)
  toDelete += [x for x in allBuildStuff
               if not path.islink(x) and not basename(x) in symlinksBuild]
  installGlob ="%s/%s/*/" % (workDir, architecture)
  installedPackages = set([dirname(x) for x in glob.glob(installGlob)])
  symlinksInstall = []
  for x in installedPackages:
    symlinksInstall += [path.realpath(y) for y in glob.glob(x + "/latest*")]
  toDelete += [x for x in glob.glob(installGlob+ "*")
               if not path.islink(x) and not path.realpath(x) in symlinksInstall]
  toDelete = [x for x in toDelete if path.exists(x)]
  return toDelete 

Example 20

def _get_script_dir(follow_symlinks: bool = True) -> Path:
    # Getting the path to the trust stores is tricky due to subtle differences on OS X, Linux and Windows
    if getattr(sys, "frozen", False):
        # py2exe, PyInstaller, cx_Freeze
        path = Path(sys.executable).absolute()
        path = Path(inspect.getabsfile(_get_script_dir))
    if follow_symlinks:
        path = Path(realpath(path))
    return path.parent 


os.path.realpath() in Python is used to get the canonical path of a specified filename by removing any symlinks found in the path .

Syntax: os.path.realpath (path)

path : A path-like object representing the file system path.
A path-like object is either a string or bytes object representing a path.

Return Type: This method returns a string value which represents the canonical path.

Create soft link or symbolic link
On Unix or Linux, a soft link or symbolic link can be created using the ln command. Following is the syntax for creating a symbolic link on the command line:

 $ ln -s {source-filename} {symbolic-filename} 



In the above output, “/ home / ihritik / Desktop / file (shortcut) .txt " is a symbolic link.

Code: using os.path.realpath () method to get canonical path and resolution symbolic links.

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

# import of the os module

import os

# Path

path = "/ home / ihritik / Desktop / file (shortcut) .txt"


# Get the canonical path
# of the specified path
# by removing any symbolic links
# met on the way

real_path = os.path.realpath (path)

# Print the canonical path

print (real_path)


# Path

path = "/../../ GeeksForGeeks / sample.py"


# Get the canonical path
# of the specified path
# elimination of any symbolic links
# met in the path

real_path = os.path.realpath (path)

# Print the canonical path

print (real_path)


# Path

path = "file.txt"


# Get the canonical path
# specified path
# remove any symbolic links
# met on the way

real_path = os .path.realpath (path)

# Print the canonical path

print (real_path)


os.chdir ( " / home / ihritik / Downloads / " )


# Path

path = "file.txt"

# Get the canonical path
# of the specified path
# elimination of any symbolic links
# met in the path

real_path = os.path.realpath (path)

# Print the canonical path

print ( real_path)


 / home / ihritik / Documents / file (original) .txt /GeeksForGeeks/sample.py /home/ihritik/file.txt /home/ihritik/Downloads/file.txt 

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

Get Solution for free from DataCamp guru