Advanced · Automation · Packages: standard library only

Project 25: Duplicate File Finder

Find files with identical content using a fast three-stage filter (size, first 4 KB, full SHA-256) and move the extra copies to a trash folder.

What you will learn

Prerequisites

Packages and installation

Packages: standard library only.

Project structure

Folder layout
duplicate_finder/
  main.py          # finder + demo
  dupes_demo/      # created by the demo run

Step-by-step build

  1. Hash a file in chunks. hash_file() reads 64 KB at a time so even a huge file never fills the memory. An optional limit hashes only the beginning.
  2. Scan the tree. scan() uses os.walk, sorts names so the order is stable and ignores symbolic links.
  3. Write a grouping helper. group_by() puts paths in a defaultdict under a key and keeps only groups with two or more files.
  4. Filter in three stages. Group by size first, then by hash of the first 4 KB, then by the full hash. Most files drop out in the cheap early stages.
  5. Report the result. report() prints each group, marks one file as keep and the rest as dup, and shows the wasted space.
  6. Quarantine duplicates. quarantine() moves duplicates into a trash folder, keeping their relative paths. Nothing is deleted for good.
  7. Create sample data. make_sample() builds files including a trap: two files with the same size and same start but a different last byte.

Complete source code

main.py
"""Duplicate File Finder: size -> partial hash -> full hash, with safe cleanup."""
import argparse
import hashlib
import os
import shutil
import sys
from collections import defaultdict
from pathlib import Path

CHUNK = 64 * 1024      # read files in 64 KB pieces
PARTIAL = 4 * 1024     # the quick check only reads the first 4 KB


def hash_file(path, limit=None):
    """SHA-256 of a file; if limit is set, only hash the first `limit` bytes."""
    digest = hashlib.sha256()
    remaining = limit
    with open(path, "rb") as handle:
        while True:
            size = CHUNK if remaining is None else min(CHUNK, remaining)
            if size == 0:
                break
            block = handle.read(size)
            if not block:
                break
            digest.update(block)
            if remaining is not None:
                remaining -= len(block)
    return digest.hexdigest()


def scan(root):
    """Walk the tree and return every regular file (sorted for stable output)."""
    found = []
    for folder, dirs, files in os.walk(root):
        dirs.sort()  # makes os.walk order predictable
        for name in sorted(files):
            path = Path(folder) / name
            if path.is_symlink() or not path.is_file():
                continue  # ignore links and special files
            found.append(path)
    return found


def group_by(paths, key_func):
    """Group paths by key_func(path) and keep only groups with 2+ files."""
    groups = defaultdict(list)
    for path in paths:
        try:
            groups[key_func(path)].append(path)
        except OSError as err:
            print(f"  skipped {path}: {err}")
    return [g for g in groups.values() if len(g) > 1]


def find_duplicates(root, min_size=1):
    """Three-stage filter: most files are ruled out by the cheap checks."""
    files = [p for p in scan(root) if p.stat().st_size >= min_size]
    stats = {"files": len(files)}
    # Stage 1: same size. Files of different sizes can never match.
    by_size = group_by(files, lambda p: p.stat().st_size)
    stats["same_size"] = sum(len(g) for g in by_size)
    # Stage 2: hash of the first 4 KB.
    candidates = [p for g in by_size for p in g]
    by_partial = group_by(candidates, lambda p: (p.stat().st_size, hash_file(p, PARTIAL)))
    stats["same_start"] = sum(len(g) for g in by_partial)
    # Stage 3: hash of the whole file.
    candidates = [p for g in by_partial for p in g]
    by_full = group_by(candidates, hash_file)
    result = sorted((sorted(g) for g in by_full), key=lambda g: str(g[0]))
    stats["duplicates"] = sum(len(g) - 1 for g in result)
    stats["wasted"] = sum(g[0].stat().st_size * (len(g) - 1) for g in result)
    return result, stats


def human(size):
    """Turn a byte count into a short readable string."""
    for unit in ("B", "KB", "MB", "GB"):
        if size < 1024 or unit == "GB":
            return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
        size /= 1024


def report(groups, stats, root):
    """Print each group of identical files, then the totals."""
    for number, group in enumerate(groups, 1):
        size = group[0].stat().st_size
        print(f"Group {number} ({human(size)} each):")
        for i, path in enumerate(group):
            label = "keep  " if i == 0 else "dup   "
            print(f"  {label}{path.relative_to(root)}")
    print(f"Scanned {stats['files']} files; {stats['same_size']} shared a size; "
          f"{stats['same_start']} shared the first 4 KB.")
    print(f"Found {stats['duplicates']} duplicates wasting {human(stats['wasted'])}.")


def quarantine(groups, root, trash):
    """Move duplicates (never the first copy) into a trash folder."""
    moved = 0
    for group in groups:
        for path in group[1:]:
            target = trash / path.relative_to(root)
            target.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(path), str(target))
            moved += 1
    return moved


def make_sample(root):
    """Create a small tree that contains known duplicates."""
    (root / "photos" / "2023").mkdir(parents=True)
    (root / "backup").mkdir()
    (root / "docs").mkdir()
    big = b"A" * 10000                      # same start, same size, different end
    big_other = b"A" * 9999 + b"B"
    files = {
        "photos/2023/cat.jpg": b"cat picture bytes" * 50,
        "backup/cat_copy.jpg": b"cat picture bytes" * 50,
        "backup/cat_copy2.jpg": b"cat picture bytes" * 50,
        "docs/notes.txt": b"meeting notes\n",
        "backup/notes_old.txt": b"meeting notes\n",
        "docs/big_a.bin": big,
        "docs/big_b.bin": big_other,            # NOT a duplicate of big_a
        "docs/unique.txt": b"only one of me\n",
        "docs/empty1.txt": b"",
        "docs/empty2.txt": b"",
    }
    for rel, data in files.items():
        (root / rel).write_bytes(data)


def run_demo():
    root = Path("dupes_demo")
    if root.exists():
        shutil.rmtree(root)
    make_sample(root / "data")
    data = root / "data"
    print("== Scan (ignoring empty files) ==")
    groups, stats = find_duplicates(data, min_size=1)
    report(groups, stats, data)
    print("== Clean up: move duplicates to trash ==")
    moved = quarantine(groups, data, root / "trash")
    print(f"Moved {moved} files")
    print("Trash holds:", sorted(str(p.relative_to(root / 'trash')) for p in scan(root / "trash")))
    groups, stats = find_duplicates(data)
    print("Scan again:", stats["duplicates"], "duplicates left")


def main():
    parser = argparse.ArgumentParser(description="Find duplicate files by content.")
    parser.add_argument("folder", nargs="?", help="folder to scan")
    parser.add_argument("--min-size", type=int, default=1, help="ignore smaller files")
    parser.add_argument("--trash", help="move duplicates into this folder")
    args = parser.parse_args()
    if not args.folder:
        run_demo()
        return
    root = Path(args.folder)
    if not root.is_dir():
        sys.exit(f"Not a folder: {root}")
    groups, stats = find_duplicates(root, args.min_size)
    report(groups, stats, root)
    if args.trash and groups:
        print("Moved", quarantine(groups, root, Path(args.trash)), "files")


if __name__ == "__main__":
    main()

Code explanation

Why three stages

Hashing every byte of every file is slow. Files with different sizes cannot be equal, so the size check is free. The 4 KB hash catches most remaining differences by reading very little. Only real candidates are fully hashed.

Chunked reading

Reading in blocks keeps memory use small. The loop updates one sha256 object block by block and stops when the limit or the end of file is reached.

defaultdict grouping

groups[key].append(path) works without checking if the key exists. A list comprehension then keeps only keys that have more than one path.

Safe cleanup

The first file in each sorted group is kept. Moving to a trash folder is reversible, which is much safer than os.remove for a first version.

Hash trap in the demo

big_a.bin and big_b.bin share a size and the first 4 KB, so they reach stage 3. The full hash correctly shows they differ.

Expected output

== Scan (ignoring empty files) ==
Group 1 (850 B each):
  keep  backup/cat_copy.jpg
  dup   backup/cat_copy2.jpg
  dup   photos/2023/cat.jpg
Group 2 (14 B each):
  keep  backup/notes_old.txt
  dup   docs/notes.txt
Scanned 8 files; 7 shared a size; 7 shared the first 4 KB.
Found 3 duplicates wasting 1.7 KB.
== Clean up: move duplicates to trash ==
Moved 3 files
Trash holds: ['backup/cat_copy2.jpg', 'docs/notes.txt', 'photos/2023/cat.jpg']
Scan again: 0 duplicates left

Common errors and solutions

Error: PermissionError or OSError while hashing
Solution: Some files cannot be read. group_by() catches OSError and prints a skipped message, so one bad file does not stop the scan.
Error: MemoryError on large files
Solution: Do not call read() on the whole file. Use chunked reads as in hash_file().
Error: Empty files reported as duplicates
Solution: All empty files are identical. Use --min-size 1 (the default) to ignore them.
Error: FileNotFoundError during cleanup
Solution: A file was moved or deleted after the scan. Scan again, or check path.exists() before moving.

Ideas to improve the project