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.6+ โ€” 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.1.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.1-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pathlib_ng-0.1.1.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.1.tar.gz
Algorithm Hash digest
SHA256 06301a38e5566151ca7e455065fc4ec2980503b8210045434fa1e03ccd37a1ba
MD5 1790296e4c1a7233911b9144f109e5a3
BLAKE2b-256 527338310bad3ef652be47413cd8043564a82fcb22ce3bf37a3972de6ebf9114

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pathlib_ng-0.1.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 55f3f42333c05da4671046033213b83bfd7bf210482bce2da82147b6707c2467
MD5 3aea6ddec612942d462a27b0616e9584
BLAKE2b-256 b0a742a6bbace04afe00f89a2845e927cd68418e122f7b83576b2ac34a10589b

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