shutil — high-level file operations

copy versus copy2 metadata, copytree, move, and rmtree, measured on Python 3.13.12 in an isolated temporary tree.

shutil is the high-level file-copy and tree module. Path construction and Path.read_text belong on the pathlib page; os.path string helpers and os.listdir belong on the os page. This page covers copy, copy2, copytree, move, and rmtree. Every operation runs inside a TemporaryDirectory created by the same script and never touches user files.

Examples were checked on Python 3.13.12 on macOS. copy and copy2 can copy additional platform metadata, such as extended attributes, that this page does not measure. The recorded facts are permission bits and modification time on this machine.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

copy, copy2, and metadata

shutil.copy(src, dst) copies file data and the permission mode. shutil.copy2 also copies metadata through copystat, including the modification time. In the example, both destinations keep mode 0o640, copy2 keeps the staged mtime 1700000000, and copy does not.

copy(src, src) raises shutil.SameFileError. The example prints only booleans and controlled names, not the current clock, so the output stays deterministic. Other platforms may copy a different metadata set; do not assume a Windows ACL or an extended attribute was or was not copied because it was not measured here.

shutil.copy, shutil.copy2

shutil.copy(src, dst, *, follow_symlinks=True)
shutil.copy2(src, dst, *, follow_symlinks=True)

Copy file data, and optionally metadata, returning the destination path.

ParameterDescription
src, dstSource path and destination path or directory. The example uses files inside one TemporaryDirectory.
follow_symlinksIf True (the default), a symlink source is followed. The example does not use symlinks.

Returns: The destination path. The example prints only the basename.

Raises

  • shutil.SameFileError — Raised when src and dst refer to the same file. Measured on Python 3.13.12.
  • copy is documented as copying data and mode bits. copy2 is documented as copying data and metadata. The mtime result was measured on this macOS Python 3.13.12 interpreter.
python
import os
import shutil
import tempfile

with tempfile.TemporaryDirectory(prefix="shutil-ref-") as base:
    src = os.path.join(base, "src.txt")
    with open(src, "w", encoding="utf-8") as file:
        file.write("payload")
    os.chmod(src, 0o640)
    os.utime(src, (1_700_000_000, 1_700_000_000))
    copied = shutil.copy(src, os.path.join(base, "copy.txt"))
    copied2 = shutil.copy2(src, os.path.join(base, "copy2.txt"))

    def mode_and_mtime(path):
        stat = os.stat(path)
        return stat.st_mode & 0o777, int(stat.st_mtime)

    src_mode, src_mtime = mode_and_mtime(src)
    copy_mode, copy_mtime = mode_and_mtime(copied)
    copy2_mode, copy2_mtime = mode_and_mtime(copied2)
    print("src-mode", oct(src_mode))
    print("copy-mode-eq", copy_mode == src_mode)
    print("copy2-mode-eq", copy2_mode == src_mode)
    print("copy-mtime-eq", copy_mtime == src_mtime)
    print("copy2-mtime-eq", copy2_mtime == src_mtime)
    print("copy-name", os.path.basename(copied))
    print("copy2-name", os.path.basename(copied2))
    with open(copied, encoding="utf-8") as file:
        print("copy-content", file.read())
    try:
        shutil.copy(src, src)
    except shutil.SameFileError as exc:
        print(type(exc).__name__)

Expected output

src-mode 0o640
copy-mode-eq True
copy2-mode-eq True
copy-mtime-eq False
copy2-mtime-eq True
copy-name copy.txt
copy2-name copy2.txt
copy-content payload
SameFileError

Related: tempfile, os

Official documentation →

copytree, move, and rmtree

copytree recursively copies a directory and, by default, raises FileExistsError if the destination already exists. dirs_exist_ok=True allows a second copy into the same destination. move relocates a file or a tree.

rmtree recursively deletes a directory tree. That is destructive and is not undoable. The example calls it only on a directory that the same script just created under TemporaryDirectory. A missing path raises FileNotFoundError unless ignore_errors=True. Do not point rmtree at a path you have not inspected.

shutil.copytree, shutil.move, shutil.rmtree

shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)
shutil.move(src, dst, copy_function=copy2)
shutil.rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None)

Copy or move a directory tree, or delete one, only inside a temporary tree you just created.

ParameterDescription
dirs_exist_okIf True, copytree may write into an existing destination. If False, an existing destination raises FileExistsError.
ignore_errorsIf True, rmtree ignores deletion errors, including a missing path. This is not a substitute for checking the path first.
onexcAn optional callback for a deletion error. onerror is the older spelling. The example does not use either callback.

Returns: copytree and move return the destination path. rmtree returns None.

Raises

  • FileExistsError — copytree when the destination exists and dirs_exist_ok is False.
  • FileNotFoundError — rmtree when the path is missing and ignore_errors is False. Measured on Python 3.13.12.
  • The recorded names are only a.txt, sub, b.txt, dst, and moved, all under the script's TemporaryDirectory.
python
import os
import shutil
import tempfile

with tempfile.TemporaryDirectory(prefix="shutil-ref-") as base:
    src = os.path.join(base, "src")
    os.mkdir(src)
    with open(os.path.join(src, "a.txt"), "w", encoding="utf-8") as file:
        file.write("A")
    os.mkdir(os.path.join(src, "sub"))
    with open(os.path.join(src, "sub", "b.txt"), "w", encoding="utf-8") as file:
        file.write("B")

    dst = shutil.copytree(src, os.path.join(base, "dst"))
    print("copytree-name", os.path.basename(dst))
    print("names", sorted(os.listdir(dst)))
    print("sub", sorted(os.listdir(os.path.join(dst, "sub"))))

    moved = shutil.move(dst, os.path.join(base, "moved"))
    print("after-move", os.path.isdir(dst), os.path.isdir(moved))

    shutil.rmtree(moved)
    print("after-rmtree", os.path.isdir(moved))
    try:
        shutil.rmtree(moved)
    except FileNotFoundError as exc:
        print("rmtree-missing", type(exc).__name__)
    shutil.rmtree(moved, ignore_errors=True)
    print("rmtree-ignore", "ok")

    shutil.copytree(src, os.path.join(base, "dst"))
    try:
        shutil.copytree(src, os.path.join(base, "dst"))
    except FileExistsError as exc:
        print("copytree-exists", type(exc).__name__)
    shutil.copytree(src, os.path.join(base, "dst"), dirs_exist_ok=True)
    print("dirs-exist-ok", os.path.isfile(os.path.join(base, "dst", "a.txt")))

Expected output

copytree-name dst
names ['a.txt', 'sub']
sub ['b.txt']
after-move False True
after-rmtree False
rmtree-missing FileNotFoundError
rmtree-ignore ok
copytree-exists FileExistsError
dirs-exist-ok True

Official documentation →