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
A lightweight, drop-in replacement for pathlib.Path with enhanced features, better error messages, and zero external dependencies.
๐ Table of Contents
- ๐ Quick Start
- โจ Features
- ๐ Usage Examples
- ๐ API Reference
- ๐ Migration from pathlib
- ๐ Project Structure
- โ๏ธ Requirements
- ๐ License
๐ 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.Pathmethods 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()andrglob()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
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pathlib_ng-0.1.3.tar.gz.
File metadata
- Download URL: pathlib_ng-0.1.3.tar.gz
- Upload date:
- Size: 6.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
32a966f12e2f1b4de124db6107b2a5ec6f07dd10d33f470b636373fcb10841fb
|
|
| MD5 |
f7dea8e171508853e96c2ed2227b14bd
|
|
| BLAKE2b-256 |
cdc08b971b1286d189ac3852c272f08a9291c873d3b1f2f35990a9c82624bb56
|
File details
Details for the file pathlib_ng-0.1.3-py3-none-any.whl.
File metadata
- Download URL: pathlib_ng-0.1.3-py3-none-any.whl
- Upload date:
- Size: 6.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0b440a1e900fdb9c603960749905ac68980e8486ac19c8b9811cb67d699bdcca
|
|
| MD5 |
9c4edba09386799fb08edbd138b050f3
|
|
| BLAKE2b-256 |
e56576a8162e0c78d79428239b83d2d489f8d3daa180cdd964a29f7031c69abb
|