c108.shutil
High-level, robust utilities for common file and directory operations.
backup_file(path, dest_dir=None, name_format='{stem}.{timestamp}{suffix}', exist_ok=False)
Creates a timestamped backup copy of a file.
Timestamps use UTC to ensure unambiguous, sortable filenames across timezones and DST transitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to the file to be backed up. |
required |
dest_dir
|
str | PathLike[str] | None
|
Directory where backup will be created. If None, uses the source file's directory. Directory must exist. |
None
|
name_format
|
str
|
Format string for backup filename. Available placeholders: - {stem}: Filename without extension (e.g., "config") - {suffix}: File extension including dot (e.g., ".txt") - {name}: Full filename (e.g., "config.txt") - {timestamp}: UTC timestamp (e.g., "20250101-143010") - {timestamp:fmt}: Formatted UTC timestamp using strftime syntax in fmt - {pid}: Process ID |
'{stem}.{timestamp}{suffix}'
|
exist_ok
|
bool
|
If False, raises FileExistsError when backup file already exists. If True, overwrites existing backup. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Absolute path to the created backup file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If source file does not exist. |
NotADirectoryError
|
If dest_dir is specified but does not exist or is not a directory. |
IsADirectoryError
|
If path points to a directory (only files are supported). |
FileExistsError
|
If backup file already exists and exist_ok=False. |
ValueError
|
If name_format contains invalid placeholders or invalid strftime format in timestamp. |
PermissionError
|
If lacking read permission on source file or write permission on destination directory. |
OSError
|
If backup operation fails due to disk space, I/O errors, or other OS-level issues. |
Examples:
>>> backup_file(file_txt)
Path('/path/to/config.20250101-143010.txt')
>>> backup_file("data.json", dest_dir="/backups", name_format="{timestamp}_{name}")
Path('/backups/20250101-143010_data.json')
>>> backup_file("log.txt", name_format="{stem}.{timestamp:%Y-%m-%d}{suffix}")
Path('/path/to/log.2025-01-01.txt')
>>> backup_file("app.log", name_format="{timestamp:%Y%m%d}_{pid}_{name}")
Path('/path/to/20250101_12345_app.log')
Source code in c108/shutil.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
clean_dir(path, *, missing_ok=False, ignore_errors=False)
Removes all contents from a directory, leaving the directory empty.
Recursively deletes all files, subdirectories, and symlinks within the directory, but preserves the directory itself (including its permissions and metadata).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Directory to empty. |
required |
missing_ok
|
bool
|
If False, raises FileNotFoundError if directory doesn't exist. If True, silently succeeds if directory is missing. |
False
|
ignore_errors
|
bool
|
If False, raises exceptions on deletion failures. If True, silently continues when individual items can't be deleted. |
False
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If path doesn't exist (when missing_ok=False). |
NotADirectoryError
|
If path exists but is not a directory. |
PermissionError
|
If lacking permission to delete contents (when ignore_errors=False). |
OSError
|
If deletion fails for other reasons (when ignore_errors=False). |
Examples:
>>> clean_dir("/tmp/cache")
>>> clean_dir("/tmp/cache", missing_ok=True)
>>> clean_dir("/tmp/cache", ignore_errors=True)
Source code in c108/shutil.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
copy_file(source, dest, *, callback=None, chunk_size=8 * 1024 * 1024, follow_symlinks=True, preserve_metadata=True, overwrite=True)
Copy file with optional progress tracking support.
Similar to shutil.copy2() but with progress tracking via callback for large files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | PathLike[str]
|
Source file path (string or PathLike object). |
required |
dest
|
str | PathLike[str]
|
Destination path (string or PathLike object). Can be a file path or directory. If directory, the file is copied into it using the source filename. |
required |
callback
|
Callable[[int, int], None] | None
|
Optional progress callback function. Signature: callback(bytes_written: int, total_bytes: int) -> None Called after each chunk is written to destination. Not called on empty files. |
None
|
chunk_size
|
int
|
Size in bytes for each copy chunk. Defaults to 8 MB. Larger chunks mean faster copies but less frequent progress updates. Set to 0 to use file_size (single chunk, minimal progress updates). |
8 * 1024 * 1024
|
follow_symlinks
|
bool
|
If True, copies the file content that symlink points to. If False, creates a new symlink at dest pointing to the same target. |
True
|
preserve_metadata
|
bool
|
If True, preserves file metadata (timestamps, permissions). Similar to shutil.copy2(). If False, only copies content like shutil.copy(). |
True
|
overwrite
|
bool
|
If False, raises FileExistsError if destination file exists. If True, overwrites existing files. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Absolute path to the destination file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If source and dest are the same file, or if chunk_size is negative. |
FileExistsError
|
If destination exists and overwrite=False. |
IsADirectoryError
|
If source is a directory (only files supported). |
Exception
|
Types propagated from Path.stat(), open(), StreamingFile, and shutil.copystat(): FileNotFoundError, PermissionError, OSError, and other I/O exceptions. |
Notes
- For files under ~1MB, progress callback overhead may exceed copy time. Consider callback=None for small files.
- The function creates parent directories of dest if they don't exist.
- When dest is a directory, behavior matches shutil.copy: the file is copied into the directory with its original basename.
- Symlink handling matches shutil.copy2 behavior by default.
- Empty files (0 bytes) are copied without calling the callback.
- Progress tracking reports bytes written to destination, which accurately reflects copy progress.
Examples:
Basic copy with progress:
>>> def progress(current, total):
... print(f"Copying: {current}/{total} bytes ({current/total*100:.1f}%)")
...
>>> copy_file("large_video.mp4", "backup/", callback=progress)
Path('/absolute/path/to/backup/large_video.mp4')
Copy to specific filename without progress:
>>> copy_file("data.csv", "archive/data_backup.csv")
Path('/absolute/path/to/archive/data_backup.csv')
Prevent overwriting existing files:
>>> copy_file("config.json", "prod/config.json", overwrite=False)
# Raises FileExistsError if prod/config.json exists
Copy with custom chunk size (faster, less frequent updates):
>>> copy_file("huge.bin", "backup/", chunk_size=64*1024*1024)
Copy without preserving metadata:
>>> copy_file("file.txt", "copy.txt", preserve_metadata=False)
Handle symlinks explicitly:
>>> # Copy symlink as symlink (don't follow)
>>> copy_file("link.txt", "copy_link.txt", follow_symlinks=False)
Source code in c108/shutil.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 | |
find_files(path, pattern='*', *, exclude=None, max_depth=None, follow_symlinks=False, include_dirs=False, predicate=None)
Find files recursively with glob-style patterns.
A more flexible alternative to glob.glob() and Path.rglob() with support for exclusion patterns, depth control, and custom filtering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Root directory to search. Must exist and be a directory. |
required |
pattern
|
str
|
Glob pattern matching against filename only. Uses fnmatch syntax: "", ".py", "test_", "[!.].txt" |
'*'
|
exclude
|
list[str] | None
|
Simple glob patterns to exclude, matching against the relative path from the search root. Uses fnmatch syntax. Common patterns: - ".pyc", ".pyo" - Compiled Python files anywhere - "pycache", ".git" - Directories anywhere - ".*" - Hidden files/directories (names starting with .) - "tests" - Anything named "tests" at any depth Note: Does NOT support ** recursive wildcard (gitignore syntax). When a directory is excluded, its entire subtree is skipped. For complex path-based exclusions, use predicate with pathspec. |
None
|
max_depth
|
int | None
|
Maximum directory depth relative to path. - None (default): Unlimited depth - 0: Only files directly in path - 1: path and immediate subdirectories |
None
|
follow_symlinks
|
bool
|
If True, follow symbolic links. Default False. |
False
|
include_dirs
|
bool
|
If True, yield directories that match pattern and are not excluded. Default False (files only). |
False
|
predicate
|
Callable[[Path], bool] | None
|
Optional callable for custom filtering. Called with each Path after pattern/exclude matching. Return True to include. |
None
|
Returns:
| Type | Description |
|---|---|
Iterator[Path]
|
Iterator[Path]: Paths to matching files (and directories if include_dirs=True). |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If path does not exist. |
NotADirectoryError
|
If path exists but is not a directory. |
Exception
|
Types propagated from os.scandir: |
Examples:
Basic usage:
>>> # Find all Python files
>>> list(find_files("src", "*.py"))
[Path('src/main.py'), Path('src/utils.py'), Path('src/tests/test_main.py')]
>>> # Exclude by name (matches anywhere in tree)
>>> list(find_files("src", "*.py", exclude=["test_*"]))
[Path('src/main.py'), Path('src/utils.py')]
>>> # Exclude directories (skips entire subtree)
>>> list(find_files(".", "*.py", exclude=["__pycache__", ".git", "venv"]))
>>> # Common Python project exclusions
>>> PYTHON_IGNORE = [
... ".*", # Hidden files/dirs
... "*.pyc", # Compiled files
... "__pycache__", # Cache dirs
... "*.egg-info", # Package metadata
... "dist", # Distribution
... "build", # Build output
... "venv", # Virtual envs
... ".venv",
... ]
>>> list(find_files(".", "*.py", exclude=PYTHON_IGNORE))
>>> # Limit search depth
>>> list(find_files("src", "*.py", max_depth=0))
[Path('src/main.py'), Path('src/utils.py')]
>>> # Include directories
>>> list(find_files("src", "cache*", include_dirs=True, exclude=[".*"]))
[Path('src/cache'), Path('src/tests/cache_temp')]
Loading exclusions from files:
>>> def load_ignore_patterns(filepath: str) -> list[str]:
... '''Load exclusion patterns from file (one per line).'''
... return [
... line.strip()
... for line in Path(filepath).read_text().splitlines()
... if line.strip() and not line.startswith('#')
... ]
>>>
>>> # File format (simple, not gitignore):
>>> # # Python build artifacts
>>> # *.pyc
>>> # __pycache__
>>> # .pytest_cache
>>> patterns = load_ignore_patterns('.buildignore')
>>> list(find_files(".", "*.py", exclude=patterns))
Gitignore-style exclusions with pathspec:
>>> # For gitignore syntax (**, negation !, trailing /), use pathspec
>>> import pathspec
>>>
>>> # Simple .gitignore usage
>>> with open('.gitignore') as f:
... spec = pathspec.PathSpec.from_lines('gitwildmatch', f)
>>> root = Path('.').resolve()
>>> files = find_files(
... ".",
... "*",
... predicate=lambda p: not spec.match_file(str(p.relative_to(root)))
... )
Advanced filtering with predicates:
>>> # Regex matching
>>> import re
>>> pattern = re.compile(r"test_.*py$")
>>> list(find_files("tests", "*.py", predicate=lambda p: pattern.search(p.name)))
>>> # File size filter
>>> large_files = find_files(
... "data",
... "*",
... exclude=[".*"],
... predicate=lambda p: p.stat().st_size > 1_000_000
... )
>>> # Modification time filter
>>> from datetime import datetime, timedelta
>>> recent = datetime.now() - timedelta(days=7)
>>> recent_logs = find_files(
... "logs",
... "*.log",
... exclude=["*.gz", "archived"],
... predicate=lambda p: datetime.fromtimestamp(p.stat().st_mtime) > recent
... )
>>> # Multiple conditions
>>> def is_recent_python_file(p: Path) -> bool:
... if p.suffix != '.py':
... return False
... age = datetime.now() - datetime.fromtimestamp(p.stat().st_mtime)
... size = p.stat().st_size
... return age.days < 30 and size > 100 and size < 100_000
>>>
>>> list(find_files("src", "*", predicate=is_recent_python_file))
Notes
- Both pattern and exclude use fnmatch syntax: *, ?, [abc], [!abc]
- Pattern matches against filename only
- Exclude patterns match against relative path from search root
- Exclude does NOT support ** (gitignore recursive wildcard)
- For gitignore-style patterns (**, !, trailing /), use pathspec library with predicate parameter (see examples above)
- When a directory matches exclude, entire subtree is skipped
- Predicate called after pattern/exclude for efficiency
- Permission errors on directories are skipped silently
- Symlink loops detected and skipped when follow_symlinks=True
See Also
pathlib.Path.rglob(): Simpler recursive globbing with ** support fnmatch.fnmatch(): Pattern matching function used for pattern/exclude pathspec library: Full gitignore syntax support for predicates
Source code in c108/shutil.py
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 | |