Skip to content
Search

Python:pathlib

lastmod 2025-02-14created 2021-09-127 edits

Path

iterdir

If the path is a directory, returns the list of all files in that directory. (Not applied recursively)

import pathlib
a = pathlib.Path('.')
for a in a.iterdir():
    print(a)

How to check whether two paths are the same location

Normalize the paths with Path.resolve and then compare them.

from pathlib import Path

a = Path("./../unwiki")
b = Path("/home/your/Project/unwiki")
a == b  # False

a.absolute()  # PosixPath('/home/your/Project/mwfilter/../unwiki')
b.absolute()  # PosixPath('/home/your/Project/unwiki')
a.absolute() == b.absolute()  # False

a.resolve()  # PosixPath('/home/your/Project/unwiki')
b.resolve()  # PosixPath('/home/your/Project/unwiki')
a.resolve() == b.resolve()  # True

How to subclass

You must set the _flavour attribute.

The Path class cannot be instantiated directly; internally it actually uses a concrete class such as PosixPath or WindowsPath depending on the OS. To work around this, specify the flavour for the current OS with something like Path('.')._flavour.

# -*- coding: utf-8 -*-

from os import PathLike
from pathlib import Path
from typing import Final, Optional, Union

DEFAULT_CVP_DIR_NAME: Final[str] = ".cvp"
DEFAULT_CVP_HOME_PATH: Final[str] = str(Path.home() / DEFAULT_CVP_DIR_NAME)


class HomeDir(Path):
    # noinspection PyUnresolvedReferences, PyProtectedMember
    _flavour = Path()._flavour

    @classmethod
    def from_path(cls, path: Optional[Union[str, PathLike[str]]] = None):
        return cls(path if path else DEFAULT_CVP_HOME_PATH)

PathFlavour class

Subclass the following class:

# -*- coding: utf-8 -*-

from pathlib import Path


class PathFlavour(Path):
    # noinspection PyProtectedMember
    _flavour = Path()._flavour  # type: ignore[attr-defined]

    def __init__(self, *_):
        super().__init__()

See also

File and Directory Access

  • Python:pathlib - Object-oriented filesystem paths
  • Python:os.path - Common pathname manipulations
  • Python:fileinput - Iterate over lines from multiple input streams
  • Python:stat - Interpreting stat() results
  • Python:filecmp - File and Directory Comparisons
  • Python:tempfile - Generate temporary files and directories
  • Python:glob - Unix style pathname pattern expansion
  • Python:fnmatch - Unix filename pattern matching
  • Python:linecache - Random access to text lines
  • Python:shutil - High-level file operations

Favorite site

author Zer0 sitemap