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)

Parameter:
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
            return

        if not spec[key]:
            logger.warning(
                "cannot resolve realpath of ’%s’ as it is not defined", key)
            return

        check = realpath(join(spec.get(WORKING_DIR, ’’), spec[key]))
        if check != spec[key]:
            spec[key] = check
            logger.warning(
                "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

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

    Returns
    -------
    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):
            self.toolchain(spec)

        with self.assertRaises(NotImplementedError):
            self.toolchain.assemble(spec)

        with self.assertRaises(NotImplementedError):
            self.toolchain.link(spec)

        # Check that the build_dir is set on the spec based on tempfile
        self.assertTrue(spec[’build_dir’].startswith(
            realpath(tempfile.gettempdir())))
        # Also that it got deleted properly.
        self.assertFalse(exists(spec[’build_dir’])) 

Example 4

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 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):
                    jdks.add(realpath(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):
                continue
            # 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)],
                             recursive=recursive))
            else:
                files.extend([op.join(file_or_dir, file)
                              for file in os.listdir(file_or_dir)])
        elif ’*’ in file_or_dir:
            files.extend(glob.glob(file_or_dir))
        else:
            files.append(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 = []
    try:
        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):
                        continue
                if baseNamesOnly:
                    subdirs.append(item)
                else:
                    subdirs.append(candidate)
    except:
        pass
    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(
        path,
        name=’10’,
        train=True,
        transform=transform,
        pre_transform=pre_transform)
    test_dataset = ModelNet(
        path,
        name=’10’,
        train=False,
        transform=transform,
        pre_transform=pre_transform)

    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’] = ’’
        else:
            parameters[’in-project’] = False
            parameters[’in-opened’] = False
            parameters[’in-dir’] = realpath(
                self.dirEditCombo.currentText().strip())
        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
    try:
        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)
        screen_handler.setFormatter(formatter)
        logger = logging.getLogger(cls.__name__)
        logger.setLevel(logging.DEBUG)
        logger.addHandler(screen_handler)

        if log_file:
            file_handler = logging.FileHandler(realpath(log_file), mode="w")
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)

        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,
                     interface=interface,
                     bro_scripts=bro_scripts)

    msg = "the cmd is: %s" % cmd
    logging.info(msg)

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

    result = run(cmd)
    logging.info(result.__dict__) 

Example 13

def ProcessFlags(env, flags):
    for f in flags:
        if f:
            env.MergeFlags(str(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[’CCFLAGS’].remove(undef)
        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
        else:
            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.

    Parameters
    ----------
    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’.

    Returns
    -------
    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

    warnings.warn(
        "Couldn’t find {0} on paths:
	{1}".format(
            lib_path,
            ’
	’.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.

    Parameters
    ----------
    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.

    Returns
    -------
    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__)
    parser.add_options([
        Option("-a", "--all",
               action="store_true",
               help="Show all dependencies, including system libs"),
        Option("-d", "--depending",
               action="store_true",
               help="Show libraries depending on dependencies")])
    (opts, paths) = parser.parse_args()
    if len(paths) < 1:
        parser.print_help()
        sys.exit(1)

    multi = len(paths) > 1
    for path in paths:
        if multi:
            print(path + ’:’)
            indent = ’   ’
        else:
            indent = ’’
        if isdir(path):
            lib_dict = tree_libs(path)
            lib_dict = stripped_lib_dict(lib_dict, realpath(getcwd()) + psep)
        else:
            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))
            continue
        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.
    assert_true(isfile(MY_PATH)) 

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()
    else:
        path = Path(inspect.getabsfile(_get_script_dir))
    if follow_symlinks:
        path = Path(realpath(path))
    return path.parent 

Archive

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)

Parameter:
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:

Example:

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)

Exit:

 / 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

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.

2973

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).

2973

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

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

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


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

2639

Answer #2


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

2639

Answer #3

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version >= 3.4

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

Path.unlink(missing_ok=False)

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

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

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

Exception Handling

#!/usr/bin/python
import os

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

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

RESPECTIVE OUTPUT

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

shutil.rmtree()

Example for shutil.rmtree()

#!/usr/bin/python
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
try:
    shutil.rmtree(mydir)
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]
print(a)

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

Traceback (most recent call last):
  File "D:zjm_codea.py", 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]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print(a)

But is there not a simpler way to do this?

1055

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]

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically