Python filecmp.cmp
Compare the contents of two small files.
A simple example
filecmp.cmp
- Start with One file contains A, another B
- Do this Compare their contents
- Result Different
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.pyCheck 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.
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")
different
Both records have three bytes, but their final digits differ.
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?
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?
What to watch for
Reading entire files into memory is appropriate only for bounded inputs.