Library contents

Python filecmp.cmp

Compare the contents of two small files.

A simple example

filecmp.cmp

  1. Start with One file contains A, another B
  2. Do this Compare their contents
  3. Result Different
They have the same length but their first bytes differ.

Syntax

Python syntax
filecmp.cmp(a, b, shallow=False)
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Check the bytes in a backup

A registrar receives a backup with the same size as its source. Compare the contents of these short records to see whether a changed final digit would be missed by a size-only check.

Resultdifferent
lesson.py
from pathlib import Path
from tempfile import TemporaryDirectory
import filecmp

with TemporaryDirectory() as folder:
    base = Path(folder)
    a, b = base / "source", base / "backup"
    a.write_bytes(b"A17")
    b.write_bytes(b"A18")
    if not filecmp.cmp(a, b, shallow=False):
        print("different")
Output
different

Both records have three bytes, but their final digits differ.

Advertisements

Prepare a gallery label

A curator stores a short UTF-8 caption beside an exhibit. Compare the note with a byte-for-byte backup immediately after copying it. What is their content relationship?

GivenFile contents “clay”
Worked resultIdentical

Prepare a studio handover

A stage manager saves a two-word instruction for the next shift. Compare the note with a byte-for-byte backup immediately after copying it. What is their content relationship?

GivenFile contents “ring bell”
Worked resultIdentical

What to watch for

Reading entire files into memory is appropriate only for bounded inputs.

Documentation for filecmp.cmp