On this page
  1. filecmp
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Comparing Two Directory Trees with dircmp
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

filecmp

Prev: fcntl | Up: stdlib_module | Next: fileinput
Rel: pathlib, os, io, time, fileinput
Ref: docs.python.org — filecmp
Tags: #public #python3 #stdlib


Import

import filecmp

Overview

File and directory comparison utilities (cmp(), cmpfiles(), and dircmp). Use filecmp to verify whether two files have identical contents or to diff two directory trees recursively for sync scripts, backup verification, and test assertions.

Quick Start

import filecmp
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    a = Path(tmp) / "a.txt"
    b = Path(tmp) / "b.txt"
    a.write_text("same content", encoding="utf-8")
    b.write_text("same content", encoding="utf-8")

    # shallow=False compares actual file bytes, not just os.stat() metadata
    assert filecmp.cmp(a, b, shallow=False) is True

Implementation Walkthrough

1. Comparing Two Directory Trees with dircmp

dircmp categorizes entries into left_only, right_only, same_files, diff_files, and subdirs (which maps subdirectory names to nested dircmp objects):

import filecmp
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    left, right = Path(tmp) / "left", Path(tmp) / "right"
    left.mkdir(); right.mkdir()
    (left / "keep.txt").write_text("v1")
    (right / "keep.txt").write_text("v1")
    (left / "changed.txt").write_text("old")
    (right / "changed.txt").write_text("new")
    (left / "only_left.txt").write_text("x")

    dc = filecmp.dircmp(left, right, shallow=False)
    assert dc.same_files == ["keep.txt"]
    assert dc.diff_files == ["changed.txt"]
    assert dc.left_only == ["only_left.txt"]

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes