Skip to content
Python Basics: Distinguish Metadata Equality from File Content Equality

Python Basics: Distinguish Metadata Equality from File Content Equality

October 28, 2026

Two files can have the same size and modification time yet contain different bytes. A controlled fixture makes the shallow comparison shortcut visible before performing a content comparison.

Prepare a scratch directory

Tested on Linux with CPython 3.12.14. You need Bash, a text editor, the named runtime, and standard mktemp, rm, and rmdir utilities. Run Python without -O so assertions remain enabled. The examples use only controlled local data; generated fixture directories are cleaned automatically.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save this as demonstrate-filecmp.py:

import filecmp
import os
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    left = Path(directory) / "left.txt"
    right = Path(directory) / "right.txt"
    left.write_bytes(b"red\n")
    right.write_bytes(b"sky\n")
    stamp = 1_700_000_000_000_000_000
    for path in (left, right):
        os.utime(path, ns=(stamp, stamp))
    print("Shallow comparison:", filecmp.cmp(left, right))
    print("Content comparison:", filecmp.cmp(left, right, shallow=False))
    assert filecmp.cmp(left, right) is True
    assert filecmp.cmp(left, right, shallow=False) is False
    right.write_bytes(left.read_bytes())
    filecmp.clear_cache()
    assert filecmp.cmp(left, right, shallow=False)
    print("After copying bytes: equal")

Run it:

python3 -B demonstrate-filecmp.py

Observed output:

Shallow comparison: True
Content comparison: False
After copying bytes: equal

Read the result

The explicit timestamps make both stat signatures match. The default shallow comparison therefore reports equality. shallow=False checks contents, revealing the difference. After copying, clearing the cache makes the final comparison fresh.

Apply it carefully

filecmp caches results using file metadata. Rapid rewrites on filesystems with coarse timestamp resolution can leave a cached answer unsuitable; clear the cache when needed. Even a fresh comparison is not a transactional snapshot if another process changes the files.

The official reference describes the behavior and options. These checks cover the fixture above rather than every input or platform.

Clean up

Remove the saved source, return to the starting directory, then remove the empty practice directory:

rm -- demonstrate-filecmp.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect its remaining contents rather than deleting unknown files.

Acknowledgements

This post was created with assistance from AI.

Last updated on