On this page
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
- Prefer
copy2()overcopy():copy2()preserves timestamps and permissions;copy()drops mtime metadata. rmtree()is permanent and recursive: Validate the target path before callingshutil.rmtree()—it bypasses the OS trash.- Never
unpack_archive()untrusted tarballs without filtering: Usetarfile.extractall(..., filter="data")directly for untrusted archives to block path traversal (../). copytree(..., dirs_exist_ok=True)(Python 3.8+) lets you merge into an existing destination directory instead of raisingFileExistsError.
Common Functions
- shutil.chown() —
chown(path, user=None, group=None, *, dir_fd=None, follow_symlinks=True)— Change owner user and group of the given path. - shutil.copy() —
copy(src, dst, *, follow_symlinks=True)— Copy data and mode bits ("cp src dst"). Return the file's destination. - shutil.copy2() —
copy2(src, dst, *, follow_symlinks=True)— Copy data and metadata. Return the file's destination. - shutil.copyfile() —
copyfile(src, dst, *, follow_symlinks=True)— Copy data from src to dst in the most efficient way possible. - shutil.copyfileobj() —
copyfileobj(fsrc, fdst, length=0)— copy data from file-like object fsrc to file-like object fdst - shutil.copymode() —
copymode(src, dst, *, follow_symlinks=True)— Copy mode bits from src to dst. - shutil.copystat() —
copystat(src, dst, *, follow_symlinks=True)— Copy file metadata Copy the permission bits, last access time, last modification time, and flags fromsrctodst. On Linux, copystat() also copies the "extended - shutil.copytree() —
copytree(src, dst, symlinks=False, ignore=None, copy_function=<function copy2 at 0x1093e0510>, ignore_dangling_symlinks=False, dirs_exist_ok=False)— Recursively copy a directory tree and return the destination directory. - shutil.disk_usage() —
disk_usage(path)— Return disk usage statistics about the given path. - shutil.get_archive_formats() —
get_archive_formats()— Returns a list of supported formats for archiving and unarchiving. - shutil.get_terminal_size() —
get_terminal_size(fallback=(80, 24))— Get the size of the terminal window. - shutil.get_unpack_formats() —
get_unpack_formats()— Returns a list of supported formats for unpacking. - shutil.ignore_patterns() —
ignore_patterns(*patterns)— Function that can be used as copytree() ignore parameter. - shutil.make_archive() —
make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None)— Create an archive file (eg. zip or tar). - shutil.move() —
move(src, dst, copy_function=<function copy2 at 0x1093e0510>)— Recursively move a file or directory to another location. This is similar to the Unix "mv" command. Return the file or directory's destination. - shutil.register_archive_format() —
register_archive_format(name, function, extra_args=None, description='')— Registers an archive format. - shutil.register_unpack_format() —
register_unpack_format(name, extensions, function, extra_args=None, description='')— Registers an unpack format. - shutil.rmtree() —
rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None)— Recursively delete a directory tree. - shutil.unpack_archive() —
unpack_archive(filename, extract_dir=None, format=None, *, filter=None)— Unpack an archive. - shutil.unregister_archive_format() —
unregister_archive_format(name)—shutil.unregister_archive_format()function. - shutil.unregister_unpack_format() —
unregister_unpack_format(name)— Removes the pack format from the registry. - shutil.which() —
which(cmd, mode=1, path=None)— Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file.
Classes & Objects
- shutil.Error —
shutil.Errorclass. (Methods:.add_note(),.with_traceback()) - shutil.SameFileError — Raised when source and destination are the same file. (Methods:
.add_note(),.with_traceback()) - shutil.SpecialFileError — Raised when trying to do a kind of operation (e.g. copying) which is not supported on a special file (e.g. a named pipe) (Methods:
.add_note(),.with_traceback())
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/shlex
- tuts/python3/stdlib_module/shutil/chown
- tuts/python3/stdlib_module/shutil/copy
- tuts/python3/stdlib_module/shutil/copy2
- tuts/python3/stdlib_module/shutil/copyfile
- tuts/python3/stdlib_module/shutil/copyfileobj
- tuts/python3/stdlib_module/shutil/copymode
- tuts/python3/stdlib_module/shutil/copystat
- tuts/python3/stdlib_module/shutil/copytree
- tuts/python3/stdlib_module/shutil/disk_usage
- tuts/python3/stdlib_module/shutil/Error
- tuts/python3/stdlib_module/shutil/get_archive_formats
- tuts/python3/stdlib_module/shutil/get_terminal_size
- tuts/python3/stdlib_module/shutil/get_unpack_formats
- tuts/python3/stdlib_module/shutil/ignore_patterns
- tuts/python3/stdlib_module/shutil/make_archive
- tuts/python3/stdlib_module/shutil/move
- tuts/python3/stdlib_module/shutil/register_archive_format
- tuts/python3/stdlib_module/shutil/register_unpack_format
- tuts/python3/stdlib_module/shutil/rmtree
- tuts/python3/stdlib_module/shutil/SameFileError
- tuts/python3/stdlib_module/shutil/SpecialFileError
- tuts/python3/stdlib_module/shutil/unpack_archive
- tuts/python3/stdlib_module/shutil/unregister_archive_format
- tuts/python3/stdlib_module/shutil/unregister_unpack_format
- tuts/python3/stdlib_module/shutil/which
- tuts/python3/stdlib_module/signal
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/popular_application_domains/automation_devops_and_web_scraping
Related notes
- tuts/python3/stdlib_module/shlex Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/chown Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/copy Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/copy2 Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/copyfile Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/copyfileobj Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/copymode Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/copystat Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/copytree Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil/disk_usage Linked here; links to this page; shared tags: #stdlib