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 FilesJava’
    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 + ""
                    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:
	’.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

" % 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 + (’
’ + indent).join(keys))
        i2 = indent + ’    ’
        for key in keys:
            print(indent + key + ’:’)
            libs = lib_dict[key]
            if len(libs):
                print(i2 + (’
’ + 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 /"


# 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/ /home/ihritik/file.txt /home/ihritik/Downloads/file.txt 

Link: https: / /

Python | os.path.realpath () method __del__: Questions

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.


Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).


Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?


Answer #1

Path objects from the Python 3.4+ pathlib module also expose these instance methods:

Python | os.path.realpath () method __delete__: Questions


Answer #2

Path objects from the Python 3.4+ pathlib module also expose these instance methods:


Answer #3

Python syntax to delete a file

import os


import os


pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")


Unlink method used to remove the file or the symbolik link.

If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.

Best practice

  1. First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
    a. os.path.isfile("/path/to/file")
    b. Use exception handling.

EXAMPLE for os.path.isfile

import os

## If file exists, delete it ##
if os.path.isfile(myfile):
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

Exception Handling

import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))


Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.

Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.

Enter file name to delete : foo.txt

Python syntax to delete a folder


Example for shutil.rmtree()

import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

Is there a simple way to delete a list element by value?

5 answers

I want to remove a value from a list if it exists in the list (which it may not).

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]

The above case (in which it does not exist) shows the following error:

Traceback (most recent call last):
  File "", line 6, in <module>
    b = a.index(6)
ValueError: list.index(x): x not in list

So I have to do this:

a = [1, 2, 3, 4]

    b = a.index(6)
    del a[b]


But is there not a simpler way to do this?


Answer #1

To remove an element"s first occurrence in a list, simply use list.remove:

>>> a = ["a", "b", "c", "d"]
>>> a.remove("b")
>>> print(a)
["a", "c", "d"]

Mind that it does not remove all occurrences of your element. Use a list comprehension for that.

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Best laptop for Zoom


Best laptop for Minecraft


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method