Python uses a variety of methods to determine if an absolute path () ω•`) o

Posted by Chesso on Tue, 23 Nov 2021 19:02:59 +0100

Python determines if the path is absolute () ω•`) o

1. What is absolute path and relative path 🍌

Absolute path:

An absolute path, also known as a full path, is a path that points to a fixed location in the file system and does not change based on the current working directory. To do this, it must include the root directory

Absolute paths can be considered a path that most people have access to. Absolute paths exist whenever they use a computer, even without programming. When you install software, you see an option to customize the installation path, which is absolute paths.

Relative path:

A relative path is based on the specified working directory, avoiding providing a complete absolute path. A file name can be considered a relative path based on the specified working directory (although it is not generally called a path).

Compare the two:

Path format characters may differ between operating systems and environments. Unix-like systems have a // directory delimiter, and Microsoft Windows systems have a / or \ directory delimiter. Here we have taken the Windows system as an example and used two forms of paths to point to a txt file:

  • Absolute path:'D:\This is a TXT file.txt'
  • Relative path: Must be in the D drive directory,. \This is a TXT file.txt or this is a TXT file.txt

2. Writing logical judgments manually

In 1, what is an absolute path, relative path content, absolute path must contain the root directory, so as to determine the benchmark, write auxiliary functions:

1) Import re regular standard library

import re

2) Determine if the root goal is included

The root directory matches the regular expression'\d+: /?|\?*', which will be used as a benchmark to determine if it is an absolute path

path = "D:\This is a txt file.txt"
print(bool(re.match(r"\d+:/?|\\?.*", path)))

3) Write it as an auxiliary function

def isabs_path(path):
    if re.match(r"\d+:/?|\\?.*", path):
        return True
    return False

Functions or methods written contain rules, and if you don't already know about regular expressions, consult the documentation

3. Use OS Standard Library to Judge Common Use

1) Import os Standard Library

import os

2) Determine whether it is an absolute path function

os.path.isabs(path)
Returns True if path is an absolute path.

path = "D:\This is a txt file.txt"
print(os.path.isabs(path))

3) Writing auxiliary functions

def isabs_path(path: str):
    """
    Determining whether it is an absolute path auxiliary function
    :param path: Text Type Path
    :return: True or False
    """
    return os.path.isabs(path)


path = "D:\This is a txt file.txt"
print(isabs_path(path))

4. Use the pathlib standard library to judge "common"

1) Import pathlib standard library

from pathlib import Path

2) Determine whether it is an absolute path method

path.is_absolute(), returns whether the path is absolute or not, and if the path has both a drive letter and a root path (if style permits), it is considered absolute

path = r"D:\This is a txt file.txt"
p_obj = Path(path)
print(p_obj.is_absolute())

3) Writing auxiliary functions

The pathlib library is an object-oriented file system path. In the example above, a path object is instantiated and its behavior is invoked
Most write paths to strings, but not is_for strings With the absolute() method, there are two possibilities for writing auxiliary function incoming parameters:

  • One is the incoming pure string path
  • Second, the incoming path object

There are three possible solutions for possible pure string paths: 🤔

  1. Determine if the incoming path belongs to the Path class

    def isabs_path(path):
        """
        Determining whether it is an absolute path auxiliary function
        :param path: Route
        :return: True or False
        """
        if issubclass(type(path), Path):
            return path.is_absolute()
        return os.path.isabs(path)
    
  2. Determine if the incoming path has is_absolute method

    def is_absolute(path):
        """
        Determining whether it is an absolute path auxiliary function
        :param path: Route
        :return: True or False
        """
        if hasattr(path, "is_absolute"):
            return getattr(path, "is_absolute")()
        return os.path.isabs(path)
    
  3. Direct instantiation to Path object

    def is_absolute(path):
        """
        Determining whether it is an absolute path auxiliary function
        :param path: Route
        :return: True or False
        """
        path = Path(path)
        return path.is_absolute()
    

Optimal solution: 😮

Seeing the end shows that you've thought a lot about it, but it's not so complicated to decide whether it's an absolute path or not.

In fact, os.path.isabs(path) can accept a path-like object after python 3.6, which means it will be recognized normally even if the path object is passed in. Then, depending on our usage scenarios and habits, we can only use os.path standard library or pathlib path object to determine whether the absolute path is the best solution. 👇

Simply import the pathlib standard library

def is_absolute(path):
    """
    Determining whether it is an absolute path auxiliary function
    :param path: Route
    :return: True or False
    """
    path = Path(path)
    return path.is_absolute()

Simply import the os standard library

def isabs_path(path: str):
    """
    Determining whether it is an absolute path auxiliary function
    :param path: Text Type Path
    :return: True or False
    """
    return os.path.isabs(path)

Reference material 💌

Related Blogs 😏

Topics: Python Operating System