path.py


Overview

`path.py` provides a comprehensive, object-oriented interface for interacting with local filesystem paths. It abstracts many common filesystem operations (reading, writing, copying, moving files/directories, querying metadata, pattern matching, and importing Python modules) into the `LocalPath` class and supporting utilities.

This file is designed to enhance and simplify filesystem manipulation beyond the standard [os.path](/projects/286/67409) and `os` modules, with portable behavior across platforms (especially POSIX and Windows). It also includes numerous utility classes and functions to support path checking, visitation, pattern matching, and hashing.

The core functionality centers around the `LocalPath` class, which represents an absolute local filesystem path and exposes a rich API for file and directory operations. The file also defines helper classes like `Checkers` for path attribute checks, `Visitor` for recursive directory traversal with filtering, and `FNMatcher` to match pathnames against glob-like patterns.


Classes and Functions

Class: LocalPath

An object-oriented wrapper around local filesystem paths that provides extensive methods for filesystem operations, path manipulation, and querying.

Key Properties and Attributes

Initialization

LocalPath(path=None, expanduser=False)

Path Manipulation Properties

Path Manipulation Methods

File and Directory Operations

Metadata and Stat

Python Import Helpers

Execution

Temporary Directory Helpers


Class: Checkers

Helper class that performs multiple attribute checks on a `LocalPath` instance (e.g., `file`, `dir`, `exists`, `link`).


Class: Visitor

Used internally by `LocalPath.visit()` to recursively generate paths filtered by filename and recursion criteria.


Class: FNMatcher

Callable class to match paths against Unix shell-style wildcards (glob patterns).


Class: Stat

Wrapper around `os.stat_result` with additional convenience methods:


Utility Functions


Important Implementation Details


Interaction with Other Parts of the System


Usage Examples

from path import local

# Create a LocalPath instance
p = local("/tmp/example.txt")

# Read text content
content = p.read_text(encoding="utf-8")

# Write binary data ensuring directories exist
p.write_binary(b"hello world", ensure=True)

# Check if file exists and is a regular file
if p.check(file=1):
    print("File exists")

# List all Python files in a directory
py_files = p.dirpath().listdir("*.py", sort=True)

# Visit all files recursively matching a pattern
for file in p.dirpath().visit(fil="*.txt", rec="*"):
    print(file)

# Import a Python module from a path
mod = p.pyimport()

# Create a unique temporary directory
tempdir = local.mkdtemp()

# Compute md5 hash of a file
md5_hash = p.computehash("md5")

Mermaid Class Diagram

classDiagram
    class LocalPath {
        -strpath: str
        +sep: str
        +__init__(path=None, expanduser=False)
        +basename
        +dirname
        +purebasename
        +ext
        +join(*args, abs=False)
        +new(**kwargs)
        +dirpath(*args, **kwargs)
        +relto(relpath)
        +common(other)
        +parts(reverse=False)
        +exists()
        +isdir()
        +isfile()
        +islink()
        +check(**kw)
        +listdir(fil=None, sort=None)
        +visit(fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False)
        +read_binary()
        +read_text(encoding)
        +write(data, mode="w", ensure=False)
        +write_binary(data, ensure=False)
        +write_text(data, encoding, ensure=False)
        +remove(rec=1, ignore_errors=False)
        +copy(target, mode=False, stat=False)
        +rename(target)
        +mkdir(*args)
        +chmod(mode, rec=0)
        +setmtime(mtime=None)
        +stat(raising=True)
        +lstat()
        +size()
        +mtime()
        +atime()
        +pypkgpath()
        +pyimport(modname=None, ensuresyspath=True)
        +sysexec(*argv, **popen_opts)
        +get_temproot()
        +mkdtemp(rootdir=None)
        +make_numbered_dir(prefix="session-", rootdir=None, keep=3, lock_timeout=172800)
    }
    class Checkers {
        -path: LocalPath
        -_statcache: Stat
        +dotfile()
        +ext(arg)
        +basename(arg)
        +basestarts(arg)
        +relto(arg)
        +fnmatch(arg)
        +endswith(arg)
        +_evaluate(kw)
        +_stat()
        +dir()
        +file()
        +exists()
        +link()
    }
    class Visitor {
        -fil: Callable or FNMatcher
        -rec: Callable or FNMatcher or None
        -ignore: Exception
        -breadthfirst: bool
        -optsort: Callable
        +__init__(fil, rec, ignore, bf, sort)
        +gen(path)
    }
    class FNMatcher {
        -pattern: str
        +__init__(pattern)
        +__call__(path)
    }
    class Stat {
        -path: LocalPath
        -_osstatresult: os.stat_result
        +size
        +mtime
        +owner
        +group
        +isdir()
        +isfile()
        +islink()
    }

    LocalPath "1" o-- "1" Checkers : uses
    LocalPath "1" o-- "*" Visitor : uses for visit()
    LocalPath "1" o-- "1" FNMatcher : uses for fnmatch
    LocalPath "1" o-- "1" Stat : uses for stat info

End of documentation for path.py