Skip to main content

Extended pathlib with 40+ additional utility methods

Project description

pathlib3

Extended pathlib with 40+ additional utility methods for Python 3.6+

pathlib3 is a powerful extension of Python's standard pathlib module. It provides a Path3 class that inherits ALL functionality from pathlib.Path while adding 40+ convenient methods for common file and directory operations.

🚀 Features

  • 100% Compatible - All pathlib.Path methods work exactly as before
  • 40+ New Methods - Additional utilities for everyday file operations
  • Type Hints - Full type hint support for better IDE experience
  • Method Chaining - Chainable methods for fluent API style
  • Zero Dependencies - Only uses Python standard library
  • Well Documented - Comprehensive docstrings with examples

📦 Installation

pip install pathlib3

Or install from source:

git clone https://github.com/cumulus13/pathlib3.git
cd pathlib3
pip install -e .

🎯 Quick Start

from pathlib3 import Path3 as Path

# Use all standard pathlib.Path methods
p = Path("myfile.txt")
p.exists()          # Standard pathlib
p.read_text()       # Standard pathlib
p.write_text("hi")  # Standard pathlib

# Plus 40+ new methods!
p.ext()                              # Get extension: "txt"
p.basename()                         # Get filename: "myfile.txt"
p.size_human()                       # Get size: "1.5 KB"
p.ensure_parent().touch()            # Create parent dirs and file
p.copy_to("backup.txt")              # Copy file
p.append_text("more content")        # Append to file
p.hash()                             # Get SHA256 hash

📚 Documentation

Basic Utilities

Get file information easily:

from pathlib3 import Path3 as Path

p = Path("/home/user/documents/report.pdf")

# File name operations
p.ext()          # "pdf" - extension without dot
p.basename()     # "report.pdf" - filename with extension
p.base()         # "report" - filename without extension  
p.dirname()      # "/home/user/documents" - directory path

# Path operations
p.abspath()      # Get absolute path as string
p.normpath()     # Normalize path (remove redundant separators)

Path Manipulation

Manipulate paths with convenient methods:

# Join paths
p = Path("/home").join("user", "documents", "file.txt")
# Result: /home/user/documents/file.txt

# Change extension
Path("file.txt").change_ext("md")        # file.md
Path("file.txt").change_ext(".json")     # file.json

# Split path
Path("/home/user/file.txt").split_ext()  # ("/home/user/file", ".txt")
Path("/home/user/file.txt").split_path() # ["/", "home", "user", "file.txt"]

Directory Operations

Work with directories efficiently:

# Create directories
Path("/tmp/new/folder").ensure_dir()     # Create if doesn't exist
Path("/tmp/new/file.txt").ensure_parent() # Create parent directories

# List directory contents
Path("/tmp").ls()                        # List all
Path("/tmp").ls("*.txt")                 # List text files only
Path("/tmp").ls(only_files=True)         # Only files
Path("/tmp").ls(only_dirs=True)          # Only directories

# Display directory tree
print(Path("/project").tree(max_depth=2))
# Output:
# /project
# ├── src/
# │   ├── main.py
# │   └── utils.py
# ├── tests/
# │   └── test_main.py
# └── README.md

# Find files recursively
Path("/tmp").find("*.py")                # Find all Python files
Path("/tmp").find_files("*.txt")         # Find text files only
Path("/tmp").find_dirs("test*")          # Find directories starting with "test"

File Operations

Perform file operations with ease:

# Copy and move
Path("source.txt").copy_to("dest.txt")
Path("source.txt").copy_to("dest.txt", overwrite=True)
Path("old.txt").move_to("new.txt")

# Create backup
Path("important.txt").backup()           # Creates important.txt.bak
Path("important.txt").backup(".backup")  # Creates important.txt.backup

# Remove files/directories
Path("file.txt").rm()                    # Remove file
Path("folder").rm(recursive=True)        # Remove directory recursively
Path("file.txt").rm(missing_ok=True)     # Don't error if doesn't exist

# Append content
Path("log.txt").append_text("New log entry\n")
Path("data.bin").append_bytes(b'\x00\x01')

# Create file with parent directories
Path("/tmp/new/folder/file.txt").touch_parent()

File Information

Get detailed file information:

# File size
Path("file.txt").size()                  # 1024 (bytes)
Path("file.txt").size_human()            # "1.0 KB"
Path("folder").size()                    # Total size of all files in folder

# Timestamps
Path("file.txt").mtime()                 # Modification time
Path("file.txt").ctime()                 # Creation time
Path("file.txt").atime()                 # Access time
Path("file.txt").age()                   # Age in seconds since last modification

# Checks
Path("file.txt").is_empty()              # True if file is empty
Path("new.txt").is_newer_than("old.txt") # Compare modification times
Path("old.txt").is_older_than("new.txt") # Compare modification times

Content Operations

Read and write various file formats:

# Read/write text with lines
lines = Path("file.txt").lines()         # Read as list of lines
lines = Path("file.txt").lines(strip=False)  # Keep whitespace

# JSON support
data = Path("config.json").read_json()
Path("output.json").write_json({"key": "value"})
Path("output.json").write_json(data, indent=4)

# Pickle support  
data = Path("data.pkl").read_pickle()
Path("data.pkl").write_pickle({"key": "value"})

# File hashing
Path("file.txt").hash()                  # SHA256 by default
Path("file.txt").hash("md5")             # MD5 hash
Path("file.txt").checksum()              # Alias for hash()

# Count lines
Path("code.py").count_lines()            # Number of lines in file

Comparison Operations

Compare files easily:

# Check if files have same content
Path("file1.txt").same_content("file2.txt")  # True if identical

Advanced Usage

Walk directory tree:

# Similar to os.walk()
for dirpath, dirnames, filenames in Path("/project").walk():
    print(f"Directory: {dirpath}")
    print(f"Subdirs: {dirnames}")
    print(f"Files: {filenames}")

Method chaining for fluent API:

# Chain multiple operations
(Path("/tmp/report/data.txt")
    .ensure_parent()
    .write_text("Report data")
    .copy_to("/backup/data.txt"))

# Create, write, and backup in one go
(Path("config.json")
    .write_json({"setting": "value"})
    .backup())

🔄 Complete Method List

Inherited from pathlib.Path

All standard methods are available: exists(), is_file(), is_dir(), mkdir(), read_text(), write_text(), glob(), rglob(), and many more.

New Methods in Path3

Basic Utilities:

  • .ext() - Get extension without dot
  • .basename() - Get filename with extension
  • .base() - Get filename without extension
  • .dirname() - Get directory path
  • .abspath() - Get absolute path as string

Path Manipulation:

  • .normpath() - Normalize path
  • .join(*args) - Join path components
  • .split_ext() - Split into base and extension
  • .split_path() - Split into components list
  • .change_ext(new_ext) - Change file extension

Directory Operations:

  • .ensure_dir() - Create directory if doesn't exist
  • .ensure_parent() - Create parent directory
  • .touch_parent() - Create parent dirs and touch file
  • .ls(pattern, only_files, only_dirs) - List contents
  • .tree(max_depth) - Display directory tree
  • .find(pattern, recursive) - Find files matching pattern

File Operations:

  • .rm(recursive, missing_ok) - Remove file/directory
  • .copy_to(dest, overwrite) - Copy to destination
  • .move_to(dest) - Move to destination
  • .append_text(text, encoding, newline) - Append text
  • .append_bytes(data) - Append bytes
  • .backup(suffix) - Create backup copy

File Information:

  • .size() - Get size in bytes
  • .size_human() - Get human-readable size
  • .mtime() - Get modification time
  • .ctime() - Get creation time
  • .atime() - Get access time
  • .age() - Get age in seconds
  • .is_empty() - Check if empty
  • .is_newer_than(other) - Compare modification times
  • .is_older_than(other) - Compare modification times

Content Operations:

  • .lines(encoding, strip) - Read lines as list
  • .read_json(encoding) - Read JSON file
  • .write_json(data, indent) - Write JSON file
  • .read_pickle() - Read pickle file
  • .write_pickle(data) - Write pickle file
  • .hash(algorithm) - Calculate file hash
  • .checksum(algorithm) - Alias for hash
  • .count_lines() - Count lines in file

Search & Filter:

  • .find_files(pattern) - Find files recursively
  • .find_dirs(pattern) - Find directories recursively
  • .walk() - Walk directory tree (like os.walk)

Comparison:

  • .same_content(other) - Check if files have same content

🆚 Comparison with Standard pathlib

Operation Standard pathlib pathlib3
Get extension p.suffix.lstrip('.') p.ext()
Get directory str(p.parent) p.dirname()
Absolute path str(p.absolute()) p.abspath()
Create parent p.parent.mkdir(parents=True, exist_ok=True) p.ensure_parent()
File size p.stat().st_size p.size()
Human size Custom function needed p.size_human()
List files list(p.glob('*')) p.ls()
Copy file shutil.copy2(p, dest) p.copy_to(dest)
Append text Open file, write, close p.append_text(text)
JSON read json.loads(p.read_text()) p.read_json()
File hash Custom implementation p.hash()
Directory tree Custom recursive function p.tree()

💡 Tips & Best Practices

Use Method Chaining

# Create a file with all parent directories
(Path("/deep/nested/structure/file.txt")
    .ensure_parent()
    .write_text("content"))

# Process and backup config
(Path("config.json")
    .read_json()
    # ... process data ...
    .write_json(processed_data)
    .backup())

Import as Path for Drop-in Replacement

# Instead of: from pathlib import Path
from pathlib3 import Path3 as Path

# Now use Path as normal, with extra methods available!

Combine with Standard pathlib Features

# Use pathlib features with Path3 extensions
p = Path.home() / "documents" / "report.txt"
p.ensure_parent().write_text("Report content")

# Glob patterns with extensions
for file in Path("/logs").find("*.log"):
    if file.age() > 86400:  # Older than 1 day
        print(f"Old log: {file.basename()} - {file.size_human()}")

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Built on top of Python's excellent pathlib module
  • Inspired by the need for more convenient path operations
  • Thanks to all contributors!

📮 Support

🔗 Links


Author

Hadi Cahyadi

Buy Me a Coffee

Donate via Ko-fi

Support me on Patreon

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

pathlib3-1.0.1.tar.gz (27.3 kB view details)

Uploaded Source

Built Distribution

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

pathlib3-1.0.1-py3-none-any.whl (13.8 kB view details)

Uploaded Python 3

File details

Details for the file pathlib3-1.0.1.tar.gz.

File metadata

  • Download URL: pathlib3-1.0.1.tar.gz
  • Upload date:
  • Size: 27.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for pathlib3-1.0.1.tar.gz
Algorithm Hash digest
SHA256 a42cee45ad1226611fe6839d9fd9307aafa17a2ce7f64fe9d3f2e418f4a87a18
MD5 ed7e906845edcf65c7c94bab2b26fdc7
BLAKE2b-256 06fd20c7c7bc77e5f3289178bf815b0cde30cfa17deed4b4e972ae4fb8aa23fb

See more details on using hashes here.

File details

Details for the file pathlib3-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: pathlib3-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 13.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for pathlib3-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b6199810e6d1eac35bd87b9f60bc53fe438920ff520e8016f2755086771d3dd7
MD5 ac2329b744ff59b6362f20a9f613b830
BLAKE2b-256 bbf73c401a8b08fd95863f2d2d3fd1d6deb818a8cf4a7a581e7cbcbfd04dc1fe

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