Python

Python shutil — Copy, Move, Archive, and Clean Up

Moving files around is half of everyday scripting: back up a folder before an edit, copy a report into a delivery folder, pack a tree into one archive, clear out a scratch folder when the job ends. The shutil module does those jobs at the level of whole files and trees, where pathlib and open work one path or one file's contents at a time. This guide copies files and trees, moves and deletes them, packs and unpacks an archive, checks disk space and program locations, and ends with the same-file, missing-file, and existing-folder traps.

Written November 13, 2026 · Tested with Python 3.12.3 · 10 min read

By the end of this guide
  • The main program: copy a file with copyfile
  • Copying into a folder: copy and copy2
  • Copying a whole tree: copytree
  • Moving and deleting: move and rmtree

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

The shutil module holds high-level file operations: copying, moving, deleting, and archiving whole files and folder trees. Where copying a file with open means reading the source and writing the destination by hand, shutil does it in one call and returns the destination path as a string. The calls take strings or path objects, and most of them follow the shape of the Unix commands with similar names, with the differences that matter spelled out in the sections below. Four moves cover most work: copy, move, delete, and archive.

The main program: copy a file with copyfile

The copyfile function copies the contents of the source file into the destination file and returns the destination path. It copies data only, no permission bits and no times:

Python
import pathlib, shutil, tempfile
with tempfile.TemporaryDirectory() as td:
    root = pathlib.Path(td)
    src = root / "notes.txt"
    src.write_text("first line\nsecond line\n", encoding="utf-8")
    dst = root / "copy.txt"
    returned = shutil.copyfile(src, dst)
    print(pathlib.Path(returned).name)
    print(dst.read_text(encoding="utf-8"), end="")
    print(src.exists(), dst.exists())
    print(dst.stat().st_size)

The exact output:

Output
copy.txt
first line
second line
True True
23

The source is still there afterward; a copy leaves both files in place. The destination must name a file, not a folder, and if a file already sits at the destination path its contents are replaced. Creating the destination folder first is the caller's job: copyfile does not create folders along the path.

Copying into a folder: copy and copy2

The copy function adds two things to copyfile: it also copies the permission bits, and its destination may be a folder, in which case the file lands inside that folder under its own name. The copy2 function goes one step further and tries to preserve all of the file metadata it can reach, including access and modification times:

Python
import pathlib, shutil, tempfile
with tempfile.TemporaryDirectory() as td:
    root = pathlib.Path(td)
    src = root / "report.txt"
    src.write_text("quarterly report\n", encoding="utf-8")
    folder = root / "out"
    folder.mkdir()
    returned = shutil.copy(src, folder)
    print(pathlib.Path(returned).name)
    print(pathlib.Path(returned).parent.name)
    print((folder / "report.txt").read_text(encoding="utf-8"), end="")
    named = shutil.copy2(src, root / "report2.txt")
    print(pathlib.Path(named).name)
    print((root / "report2.txt").stat().st_size == src.stat().st_size)

The exact output:

Output
report.txt
out
quarterly report
report2.txt
True

The return value answers where the file actually landed, which matters when the destination was a folder: the program reads the name and the parent folder off the returned path instead of guessing. Pick copy2 when the copy should look like the original to tools that sort or sync by modification time, such as a backup step; pick copyfile when only the contents matter and nothing should carry over.

Copying a whole tree: copytree

The copytree function copies a folder and everything under it, subfolders included, and creates the destination folder itself. It returns the destination path:

Python
import pathlib, shutil, tempfile
with tempfile.TemporaryDirectory() as td:
    root = pathlib.Path(td)
    src = root / "site"
    (src / "sub").mkdir(parents=True)
    (src / "a.txt").write_text("a\n", encoding="utf-8")
    (src / "sub" / "b.txt").write_text("b\n", encoding="utf-8")
    dst = root / "site-copy"
    returned = shutil.copytree(src, dst)
    print(pathlib.Path(returned).name)
    print(sorted(str(p.relative_to(dst)) for p in dst.rglob("*") if p.is_file()))
    print((dst / "sub" / "b.txt").read_text(encoding="utf-8"), end="")

The exact output:

Output
site-copy
['a.txt', 'sub/b.txt']
b

Files inside the tree are copied with copy2, so their metadata comes along. Symbolic links are followed by default and the files they point at are copied; passing symlinks as true copies the links themselves instead. By default the destination must not exist yet, which is the trap covered at the end of this guide.

Moving and deleting: move and rmtree

The move function moves a file or a tree and returns the destination. Given a new file path it renames as it moves; given an existing folder it moves the file inside that folder under its own name. The rmtree function deletes a folder and everything under it:

Python
import pathlib, shutil, tempfile
with tempfile.TemporaryDirectory() as td:
    root = pathlib.Path(td)
    src = root / "old.txt"
    src.write_text("data\n", encoding="utf-8")
    moved = shutil.move(src, root / "new.txt")
    print(src.exists())
    print(pathlib.Path(moved).name)
    folder = root / "dest"
    folder.mkdir()
    moved2 = shutil.move(root / "new.txt", folder)
    print(pathlib.Path(moved2).parent.name, pathlib.Path(moved2).name)
    junk = root / "junk"
    (junk / "sub").mkdir(parents=True)
    (junk / "sub" / "x.txt").write_text("x\n", encoding="utf-8")
    shutil.rmtree(junk)
    print(junk.exists())

The exact output:

Output
False
new.txt
dest new.txt
False

After a move the old path is gone, which is the plain difference from a copy. A move across filesystems cannot be a rename, so shutil copies the tree to the destination and then deletes the source. The rmtree call has no undo and asks for no confirmation: the last two lines of the program show the folder simply no longer existing. Programs that delete trees check the path they are about to pass one more time before the call, because a wrong variable is all it takes.

Packing and unpacking: make_archive and unpack_archive

The make_archive function packs a folder into a single archive file and returns the archive path. The format name picks the kind of archive; zip and the tar family are the usual choices, and the root_dir and base_dir arguments say which folder to pack, counted from where. The unpack_archive function reverses the job:

Python
import pathlib, shutil, tempfile
with tempfile.TemporaryDirectory() as td:
    root = pathlib.Path(td)
    data = root / "data"
    data.mkdir()
    (data / "notes.txt").write_text("hello shutil\n", encoding="utf-8")
    made = shutil.make_archive(str(root / "pack"), "zip", root_dir=root, base_dir="data")
    print(pathlib.Path(made).name)
    out = root / "out"
    shutil.unpack_archive(made, out)
    print(sorted(str(p.relative_to(out)) for p in out.rglob("*") if p.is_file()))
    print((out / "data" / "notes.txt").read_text(encoding="utf-8"), end="")
    print("zip" in dict(shutil.get_archive_formats()))

The exact output:

Output
pack.zip
['data/notes.txt']
hello shutil
True

The archive kept the data folder as its top entry, because base_dir names the folder to store, and unpacking rebuilt that folder under the output path. The get_archive_formats function lists the formats this Python can write, so a program can check for a format instead of assuming it. For entry-by-entry control over a zip archive — names, compression, reading one entry without unpacking — the zipfile module is the tool; make_archive is the one-call version of the common job.

Disk space and program lookup: disk_usage and which

The disk_usage function returns a named tuple with total, used, and free bytes for the filesystem holding the given path. The which function searches the system path for a program and returns its full path, or None when no such program is on the path:

Python
import pathlib, shutil, tempfile
with tempfile.TemporaryDirectory() as td:
    usage = shutil.disk_usage(td)
    print(type(usage).__name__)
    print(usage.total > 0)
    print(usage.free > 0)
    print(usage.free <= usage.total)
    found = shutil.which("python3")
    print(pathlib.Path(found).name)
    print(shutil.which("no-such-program-veldica"))

The exact output:

Output
usage
True
True
True
python3
None

The three disk numbers are sizes in bytes and they move as the machine works, so the program prints checks on them rather than the numbers themselves. A script that writes a large backup tests free against the size it needs before it starts, not after the write fails halfway. The which call is the same check a person runs at a shell prompt, and a None result lets a program print a clear message about the missing tool instead of failing later with a file-not-found error from a subprocess.

Three traps: a missing source, the same file twice, and a folder that already exists

Trap
Copying from a path that does not exist raises FileNotFoundError. Copying a file onto itself raises SameFileError. Calling copytree onto a folder that already exists raises FileExistsError, until dirs_exist_ok is passed as true, which merges the tree into the existing folder. Handing rmtree a file instead of a folder raises NotADirectoryError:
Python
import pathlib, shutil, tempfile
with tempfile.TemporaryDirectory() as td:
    root = pathlib.Path(td)
    src = root / "a.txt"
    src.write_text("a\n", encoding="utf-8")
    try:
        shutil.copyfile(root / "missing.txt", root / "b.txt")
    except FileNotFoundError as error:
        print(type(error).__name__)
    try:
        shutil.copyfile(src, src)
    except shutil.SameFileError as error:
        print(type(error).__name__)
    tree = root / "tree"
    tree.mkdir()
    (tree / "f.txt").write_text("f\n", encoding="utf-8")
    dest = root / "dest"
    shutil.copytree(tree, dest)
    try:
        shutil.copytree(tree, dest)
    except FileExistsError as error:
        print(type(error).__name__)
    shutil.copytree(tree, dest, dirs_exist_ok=True)
    print((dest / "f.txt").read_text(encoding="utf-8"), end="")
    try:
        shutil.rmtree(src)
    except NotADirectoryError as error:
        print(type(error).__name__)

The exact output:

Output
FileNotFoundError
SameFileError
FileExistsError
f
NotADirectoryError

Each of these is cheap to meet in a first test and expensive to meet in a cleanup script that runs unattended. The same-file case is the quiet one in real code: it appears when a destination path is built from the same variable as the source, such as copying a folder of files into itself. The dirs_exist_ok setting is a choice, not a default to reach for — merging into an existing folder leaves files from both trees mixed, which is right for adding files to a delivery folder and wrong for making a clean copy.

Which choice for which job

Job Choice Why
Contents only copyfile No metadata carries over
Copy into a folder copy Folder destination allowed
Keep file times copy2 Metadata preserved
Whole folder tree copytree Creates and fills the tree
Rename or relocate move Old path ends up gone
Delete a tree rmtree Removes folder and contents
One archive file make_archive Pack a folder in one call
Check space first disk_usage Free bytes before writing
Find a program which Full path or None

Checklist

  • Before a copy, confirm the source exists and the destination folder exists; copyfile creates neither folders nor sources.
  • Before copying a file onto a path built in code, check the two paths are not the same file.
  • Before a copytree, decide whether an existing destination is an error or a merge, and set dirs_exist_ok to match that decision.
  • Before an rmtree, print or log the exact path about to be deleted; there is no undo.
  • Before writing a large output, compare disk_usage free bytes against the size the job needs.
  • Before running an external program, resolve it with which and handle the None case with a clear message.

Sources

  • Python Standard Library, shutil — copyfile, copy and copy2, copytree and dirs_exist_ok, move, rmtree, make_archive and unpack_archive with get_archive_formats, disk_usage, which, and the SameFileError error.
  • Python Standard Library, pathlib — the Path objects used for the source, destination, and tree paths.

Keep Exploring