Python Python Free

Python: Find and Remove Duplicate Files by Hash

Find duplicate files in a folder by comparing their content hash — same content, different name, caught every time.

24 lines · Updated Nov 26, 2026

Preview of Python: Find and Remove Duplicate Files by Hash
python-remove-duplicate-files.py
import hashlib
from pathlib import Path

def file_hash(path, chunk_size=65536):
    digest = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            digest.update(chunk)
    return digest.hexdigest()

def find_duplicates(folder):
    seen = {}
    for path in Path(folder).rglob("*"):
        if not path.is_file():
            continue
        key = file_hash(path)
        seen.setdefault(key, []).append(path)
    return [group for group in seen.values() if len(group) > 1]

if __name__ == "__main__":
    for group in find_duplicates("Downloads"):
        print("Duplicates:")
        for path in group:
            print(" ", path)

About this snippet

Duplicate files waste gigabytes: the same photo downloaded twice, backups copied into backups, "final (2).pdf". Comparing file names does not work, because duplicates often have different names. This snippet finds true duplicates by comparing a hash of each file's contents, then lets you review or remove the extra copies.

How it works

  1. It walks through a folder and its sub-folders.
  2. To be fast, it first groups files by size — files with different sizes cannot be identical.
  3. For files with the same size, it computes a SHA-256 hash, reading the file in chunks so even large videos do not fill your memory.
  4. Files with the same hash are identical. The script keeps one and reports or removes the rest.

How to use it safely

  1. Run in report-only (dry-run) mode first and read the list.
  2. Back up important folders before deleting anything.
  3. Prefer moving duplicates into a "duplicates" folder rather than deleting them, then empty it once you are sure.

Customize it

  • Decide which copy to keep — the oldest, the newest or the one in a preferred folder.
  • Skip system folders and file types you never want to touch.
  • Export the results to CSV for review in Excel.

Common problems

  • Similar photos not detected: hashing finds identical files only. Resized or edited images need perceptual hashing (for example the imagehash package).
  • PermissionError: skip files you cannot read instead of stopping the whole run.

FAQ

Is MD5 good enough? For finding accidental duplicates it works, but SHA-256 is the safer default and is still fast.

Related: Organize Downloads by file type · 10 Python automation projects

How to install

Run it on a copy of a small folder first. It only lists duplicates — delete them yourself after checking, or add a --delete flag that keeps the first file of each group.

Share this snippet

See all
Chat with us