Universal Pathlib
Universal Pathlib is a Python library that extends the `pathlib.Path` interface to provide a unified, Pythonic way of interacting with a wide variety of backend filesystems, including local, cloud storage (S3, GCS, Azure), HTTP(S), and more, by leveraging `fsspec` backends. It is currently at version 0.3.10 and maintains a regular release cadence with frequent updates and bug fixes.
Warnings
- breaking The `_protocol_dispatch=False` argument for extending the UPath API has been deprecated. Using it may lead to incorrect behavior or be removed in future versions.
- gotcha Attempting to instantiate a specific `UPath` subclass (e.g., `S3Path`) with a path string for a different protocol (e.g., `http://` or `file://`) will now raise a `TypeError` due to protocol incompatibility, rather than silently failing or using an incorrect backend.
- gotcha While `UPath` can attempt to handle any `fsspec`-compatible protocol, explicit implementations are tested and guaranteed. If no specialized `UPath` implementation exists for a given protocol, `UPath` will return a generic instance, but its behavior might not be fully reliable or tested.
Install
-
pip install universal-pathlib -
pip install universal-pathlib fsspec[s3,gcs]
Imports
- UPath
from upath import UPath
Quickstart
import os
from upath import UPath
# Example for S3 (requires 's3fs' to be installed and AWS credentials configured)
# You can use environment variables for credentials or pass storage_options
S3_BUCKET = os.environ.get('S3_TEST_BUCKET', 'your-test-s3-bucket')
S3_KEY = 'example.txt'
# Create a UPath object for an S3 location
s3path = UPath(f"s3://{S3_BUCKET}") / S3_KEY
# Write content to the S3 file
try:
s3path.write_text('Hello from Universal Pathlib!')
print(f"Successfully wrote to {s3path}.")
# Read content from the S3 file
content = s3path.read_text()
print(f"Content of {s3path}: '{content}'.")
# Check if the path exists
print(f"Does {s3path} exist? {s3path.exists()}.")
# List contents of the parent directory (if bucket exists and is not empty)
print(f"Listing contents of {s3path.parent}:")
for p in s3path.parent.iterdir():
print(f" - {p}")
finally:
# Clean up: delete the created file
if s3path.exists():
s3path.unlink()
print(f"Cleaned up: deleted {s3path}.")
# Example for a local file (no additional fsspec backend needed)
local_path = UPath("local_example.txt")
local_path.write_text("This is a local file.")
print(f"Local file content: {local_path.read_text()}")
local_path.unlink()