Python: Merge Multiple PDFs into One
Merge several PDF files into one with Python in a few lines — keep the page order you choose.
Find duplicate files in a folder by comparing their content hash — same content, different name, caught every time.
24 lines · Updated Nov 26, 2026
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)
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.
imagehash package).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
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
Merge several PDF files into one with Python in a few lines — keep the page order you choose.
Read the text out of any PDF with Python — the first step for search, summaries and automation.
Send yourself a Telegram message from Python — free alerts for scripts, servers and price trackers.