On this page
  1. shutil
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Copying Trees with Exclusions & Safe Cleanup
  7. 2. Creating & Extracting Archives
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

shutil

Prev: shlex | Up: stdlib_module | Next: signal
Rel: pathlib, os, io, time, fileinput
Ref: docs.python.org — shutil
Tags: #public #python3 #stdlib


Import

import shutil

Overview

High-level filesystem operations built on top of os: copying files with metadata (copy2), copying or deleting entire directory trees (copytree, rmtree), moving across filesystems (move), finding executables on PATH (which), and creating/unpacking zip/tar archives.

Quick Start

import shutil

python_bin = shutil.which("python3")
usage = shutil.disk_usage("/")
assert usage.total > 0

Implementation Walkthrough

1. Copying Trees with Exclusions & Safe Cleanup

from pathlib import Path
import shutil
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    src = Path(tmp) / "src"
    dst = Path(tmp) / "dst"
    src.mkdir()
    (src / "app.py").write_text("print('hi')\n", encoding="utf-8")
    (src / "debug.pyc").write_bytes(b"")

    shutil.copytree(src, dst, ignore=shutil.ignore_patterns("*.pyc", "__pycache__"))
    assert (dst / "app.py").exists() and not (dst / "debug.pyc").exists()

2. Creating & Extracting Archives

import shutil

# Creates /tmp/release.zip from ./build_dir
# archive_path = shutil.make_archive("/tmp/release", "zip", root_dir="build_dir")
# shutil.unpack_archive(archive_path, extract_dir="/tmp/unpacked")

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes