A Python utility belt containing simple tools, a stdlib like feel, and extra batteries
Cross-platform path utilities, file operations, symbolic links, and temporary directory management with enhanced pathlib functionality.
Extended pathlib.Path with additional methods for common operations.
class Path(pathlib.Path):
"""
Enhanced pathlib.Path with additional methods and cross-platform compatibility.
"""
def augment(self, prefix='', suffix='', ext=None, **kwargs): ...
def shrinkuser(self): ...
def expanduser(self): ...
def ensuredir(self, **kwargs): ...
def augpath(path, prefix='', suffix='', ext=None, base=None, dpath=None, fname=None, **kwargs):
"""
Augment path components (directory, filename, extension).
Args:
path (str|Path): Original path
prefix (str): Add prefix to filename
suffix (str): Add suffix to filename (before extension)
ext (str): Change or add file extension
base (str): Replace filename base
dpath (str): Replace directory path
fname (str): Replace entire filename
Returns:
str: Augmented path
"""
def expandpath(path):
"""
Expand ~ and environment variables in path.
Args:
path (str): Path to expand
Returns:
str: Expanded path
"""
def shrinkuser(path):
"""
Replace home directory with ~ in path.
Args:
path (str): Path to shrink
Returns:
str: Path with ~ substitution
"""
def userhome():
"""
Get user home directory.
Returns:
str: User home directory path
"""Functions for creating, managing, and working with directories.
def ensuredir(dpath, mode=0o755, **kwargs):
"""
Ensure directory exists (mkdir -p equivalent).
Args:
dpath (str|Path): Directory path to create
mode (int): Directory permissions (Unix only)
**kwargs: Additional options
Returns:
str: The directory path that was ensured
"""
class TempDir:
"""
Context manager for temporary directories.
"""
def __init__(self, suffix='', prefix='tmp', dir=None): ...
def __enter__(self): ...
def __exit__(self, exc_type, exc_val, exc_tb): ...
@property
def dpath(self): ...
class ChDir:
"""
Context manager for changing directories.
"""
def __init__(self, dpath): ...
def __enter__(self): ...
def __exit__(self, exc_type, exc_val, exc_tb): ...Basic file manipulation including creation, deletion, and metadata operations.
def touch(fpath, mode=0o644, dir_fd=None, **kwargs):
"""
Create empty file or update timestamp.
Args:
fpath (str|Path): File path to touch
mode (int): File permissions
dir_fd: Directory file descriptor
**kwargs: Additional options
Returns:
str: Path of touched file
"""
def delete(fpath, **kwargs):
"""
Delete file or directory.
Args:
fpath (str|Path): Path to delete
**kwargs: Additional options (recursive, etc.)
Returns:
None
"""Cross-platform symbolic link creation with Windows compatibility.
def symlink(real_path, link_path, overwrite=False, **kwargs):
"""
Create symbolic link (cross-platform).
Args:
real_path (str|Path): Target path
link_path (str|Path): Link path to create
overwrite (bool): Overwrite existing link
**kwargs: Additional platform-specific options
Returns:
str: Path of created link
Note:
On Windows, may require administrator privileges or developer mode.
Falls back to hard links or copying if symbolic links fail.
"""def readfrom(fpath, **kwargs):
"""
Read text from file.
DEPRECATED: Use Path(fpath).read_text() or open() instead.
Args:
fpath (str|Path): File to read
**kwargs: Additional options
Returns:
str: File contents
"""
def writeto(fpath, to_write, **kwargs):
"""
Write text to file.
DEPRECATED: Use Path(fpath).write_text() or open() instead.
Args:
fpath (str|Path): File to write
to_write (str): Content to write
**kwargs: Additional options
Returns:
None
"""import ubelt as ub
# Augment path components
original = '/home/user/document.txt'
# Add suffix before extension
backup = ub.augpath(original, suffix='_backup')
# Result: '/home/user/document_backup.txt'
# Change extension
config = ub.augpath(original, ext='.json')
# Result: '/home/user/document.json'
# Add prefix and change directory
new_path = ub.augpath(original, prefix='old_', dpath='/archive')
# Result: '/archive/old_document.txt'
# Multiple modifications
result = ub.augpath(original, prefix='backup_', suffix='_v2', ext='.bak')
# Result: '/home/user/backup_document_v2.bak'import ubelt as ub
# Basic temporary directory
with ub.TempDir() as tmp:
print(f"Temp dir: {tmp.dpath}")
# Create files in temp directory
temp_file = tmp.dpath / 'example.txt'
ub.touch(temp_file)
# Use Path operations
temp_path = ub.Path(tmp.dpath)
files = list(temp_path.iterdir())
print(f"Files: {files}")
# Directory is automatically cleaned up
# Custom temporary directory
with ub.TempDir(prefix='myapp_', suffix='_work') as tmp:
# Work with temporary directory
work_dir = ub.ensuredir(tmp.dpath, 'subdir')
config_file = ub.Path(work_dir) / 'config.json'
config_file.write_text('{"setting": "value"}')import ubelt as ub
# Ensure directory exists
project_dir = ub.ensuredir('~/projects/myapp')
data_dir = ub.ensuredir(project_dir, 'data')
cache_dir = ub.ensuredir(project_dir, 'cache')
# Change directory context
original_dir = ub.Path.cwd()
with ub.ChDir('/tmp'):
print(f"Current dir: {ub.Path.cwd()}")
# Do work in /tmp
ub.touch('temp_file.txt')
print(f"Back to: {ub.Path.cwd()}") # Back to original directoryimport ubelt as ub
# Create empty files
ub.touch('new_file.txt')
ub.touch('config/settings.ini') # Creates parent dirs if needed
# Cross-platform symbolic links
ub.symlink('/path/to/original', '/path/to/link')
# Safe deletion
try:
ub.delete('old_file.txt')
ub.delete('old_directory') # Works for directories too
except FileNotFoundError:
print("File didn't exist")import ubelt as ub
# Home directory operations
home = ub.userhome()
config_path = ub.Path(home) / '.config' / 'myapp'
# Expand user paths
expanded = ub.expandpath('~/documents/project')
# Shrink paths for display
display_path = ub.shrinkuser('/home/user/very/long/path')
# Result: '~/very/long/path'
# Enhanced Path class
path = ub.Path('~/documents/file.txt').expanduser()
parent = path.parent
stem = path.stem
suffix = path.suffiximport ubelt as ub
# Normalize paths
path1 = ub.Path('./documents/../documents/file.txt').resolve()
path2 = ub.Path('documents/file.txt').resolve()
assert path1 == path2
# Cross-platform path handling
if ub.WIN32:
# Windows path handling
path = ub.Path('C:\\Users\\Name\\Documents')
else:
# Unix path handling
path = ub.Path('/home/user/documents')
# Always works regardless of platform
normalized = path.expanduser().resolve()Install with Tessl CLI
npx tessl i tessl/pypi-ubelt