Skip to main content

A lightweight, drop-in replacement for `pathlib.Path` with enhanced features, better error messages, and zero external dependencies

Project description

pathlib-ng โ€” Enhanced Path implementation

Python PyPI License Platform Ruff

A lightweight, drop-in replacement for pathlib.Path with enhanced features, better error messages, and zero external dependencies.


๐Ÿ“‘ Table of Contents


๐Ÿš€ Quick Start

pip install pathlib-ng
from pathlib_ng import Path

# Create paths with intuitive syntax
p = Path("projects") / "docs" / "readme.md"

# Read file content
if p.exists() and p.is_file():
    content = p.read_text()
    print(f"Content length: {len(content)} characters")
    print(f"File size: {p.stat().st_size} bytes")

# Work with path components
print(f"Name: {p.name}")           # readme.md
print(f"Stem: {p.stem}")           # readme
print(f"Suffix: {p.suffix}")       # .md
print(f"Parent: {p.parent}")       # projects/docs

โœจ Features

  • Complete API โ€” All standard pathlib.Path methods implemented
  • Path concatenation โ€” Overloaded / operator for intuitive path building
  • File I/O โ€” read_text(), write_text(), read_bytes(), write_bytes()
  • Directory operations โ€” mkdir(), rmdir(), iterdir()
  • Glob patterns โ€” glob() and rglob() for file matching
  • Path resolution โ€” resolve(), absolute(), expanduser()
  • File metadata โ€” stat(), exists(), is_file(), is_dir()
  • File management โ€” rename(), unlink(), touch()
  • Cross-platform โ€” Works on Linux, macOS, and Windows
  • Zero dependencies โ€” Pure Python with standard library only
  • Type hints โ€” Full typing support for better IDE integration

๐Ÿ“– Usage Examples

Creating Paths

from pathlib_ng import Path

# Various ways to create paths
p1 = Path("docs/readme.md")
p2 = Path("projects", "src", "main.py")
p3 = Path("/usr", "local", "bin")
p4 = Path.home() / "Documents" / "file.txt"
p5 = Path.cwd() / "data" / "output.json"

# Path concatenation with / operator
p = Path("projects") / "src" / "utils"

Path Properties

p = Path("projects/docs/readme.md")

print(p.parent)      # projects/docs
print(p.name)        # readme.md
print(p.stem)        # readme
print(p.suffix)      # .md
print(p.anchor)      # (empty string for relative path)

File I/O

p = Path("data.txt")

# Write and read text
p.write_text("Hello, World!", encoding="utf-8")
content = p.read_text()  # "Hello, World!"

# Write and read bytes
p.write_bytes(b"Binary data")
data = p.read_bytes()    # b"Binary data"

# Append to file
with open(p, "a") as f:
    f.write("Appended text")

Directory Operations

# Create directories
p = Path("projects/my_app/data")
p.mkdir(parents=True, exist_ok=True)  # Creates all parent directories

# Iterate directory contents
for item in p.parent.iterdir():
    if item.is_file():
        print(f"File: {item.name}")
    elif item.is_dir():
        print(f"Directory: {item.name}")

# Remove empty directory
p.rmdir()

# Get working directories
cwd = Path.cwd()
home = Path.home()

File Management

p = Path("file.txt")

# Create empty file
p.touch()
p.touch(exist_ok=False)  # Raises FileExistsError if exists

# Check existence
p.exists()      # True/False
p.is_file()     # True/False
p.is_dir()      # True/False

# Rename
p.rename("renamed.txt")

# Delete
p.unlink()
p.unlink(missing_ok=True)  # No error if file doesn't exist

# Get file stats
stat = p.stat()
print(f"Size: {stat.st_size} bytes")
print(f"Modified: {stat.st_mtime}")

Path Resolution

# Resolve to absolute path (with symlinks resolved)
p = Path("docs/../src/main.py")
resolved = p.resolve()  # /absolute/path/src/main.py

# Get absolute path without resolving symlinks
absolute = p.absolute()  # /current/working/dir/docs/../src/main.py

# Expand user home directory
p = Path("~/Documents/file.txt")
expanded = p.expanduser()  # /home/username/Documents/file.txt

Glob Patterns

# Find all Python files
for py_file in Path.cwd().glob("*.py"):
    print(py_file)

# Find all .txt files recursively
for txt_file in Path.cwd().rglob("*.txt"):
    print(txt_file)

# Find all directories
for dir in Path.cwd().glob("*/"):
    print(dir.name)

# Complex pattern matching
Path.cwd().glob("src/**/*.py")  # All Python files in src/ and subdirectories

๐Ÿ”„ Migration from pathlib

pathlib-ng is designed as a drop-in replacement. Most code works with minimal changes:

# Standard pathlib
from pathlib import Path

# pathlib-ng
from pathlib_ng import Path

# Everything else remains the same!
p = Path("/tmp/test")
p.mkdir(exist_ok=True)
p.write_text("Hello")

๐Ÿ†• Additional Features

pathlib-ng includes several enhancements over standard pathlib:

Enhanced Error Messages

try:
    Path("/nonexistent/file.txt").read_text()
except FileNotFoundError as e:
    print(e)  # Clear, descriptive error message

Additional Utility Methods

# Get absolute path as string
path_str = Path("file.txt").absolute_path()

# Create all parents automatically with touch()
Path("deep/nested/file.txt").touch()  # Creates parent directories

Better Cross-Platform Support

  • Handles path separators consistently across platforms
  • Properly normalizes paths for Windows and Unix

๐Ÿ“ Project Structure

pathlib-ng/
โ”œโ”€โ”€ pathlib_ng/
โ”‚   โ”œโ”€โ”€ __init__.py      # Package exports
โ”‚   โ””โ”€โ”€ path.py          # Path class implementation
โ”œโ”€โ”€ LICENSE              # MIT License
โ”œโ”€โ”€ pyproject.toml       # Project metadata
โ””โ”€โ”€ README.md            # This file

๐Ÿ’ก Real-World Examples

Recursive File Search

from pathlib_ng import Path

def find_files(directory, extension):
    """Find all files with given extension recursively."""
    return list(Path(directory).rglob(f"*.{extension}"))

txt_files = find_files(".", "txt")
for f in txt_files:
    print(f"Found: {f}")

Project Structure Validation

from pathlib_ng import Path

project = Path("my_project")
required_dirs = ["src", "tests", "docs"]
required_files = ["README.md", "pyproject.toml"]

# Check directories
for dir_name in required_dirs:
    dir_path = project / dir_name
    if not dir_path.exists():
        print(f"Missing directory: {dir_name}")
        dir_path.mkdir(parents=True)

# Check files
for file_name in required_files:
    file_path = project / file_name
    if not file_path.exists():
        print(f"Missing file: {file_name}")
        file_path.touch()

Batch File Processing

from pathlib_ng import Path

def process_logs(log_dir):
    """Process all log files in a directory."""
    log_dir = Path(log_dir)
    
    for log_file in log_dir.glob("*.log"):
        # Read and process
        content = log_file.read_text()
        processed = content.upper()
        
        # Write processed version
        processed_file = log_file.with_suffix(".processed.log")
        processed_file.write_text(processed)
        
        # Archive original
        archive_dir = log_dir / "archive"
        archive_dir.mkdir(exist_ok=True)
        log_file.rename(archive_dir / log_file.name)

โš™๏ธ Requirements

  • Python 3.10+ โ€” Uses modern Python features
  • No external dependencies โ€” Pure Python with standard library only

๐Ÿ“„ License

MIT License โ€” Use freely in open source and commercial projects.

Author: Fkernel653

Links: GitHub โ€ข PyPI

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pathlib_ng-0.1.0.tar.gz (6.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pathlib_ng-0.1.0-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

Details for the file pathlib_ng-0.1.0.tar.gz.

File metadata

  • Download URL: pathlib_ng-0.1.0.tar.gz
  • Upload date:
  • Size: 6.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for pathlib_ng-0.1.0.tar.gz
Algorithm Hash digest
SHA256 241dbf775624ca396e7b0acb78fa4beaf5d98fa839cddfe3337165846c5024ab
MD5 a3e3927d6e3cb3975064a51cbce8f30f
BLAKE2b-256 93dbee3d68bf5d5d05ee88a31edd55a0915b79088c0ed7a35ed5bd54f0c3a4e7

See more details on using hashes here.

File details

Details for the file pathlib_ng-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: pathlib_ng-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for pathlib_ng-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 abe8886c475d372418e283d3e160737746e23c864c51e24f81ab48c94fb87d3a
MD5 4a04a82a533590f633e0982c338bb2f3
BLAKE2b-256 3ad8f75758af3828f7a394351c5377e0ddf34dceabd543f7a30d52bde3df50ef

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page