Skip to content
Foxipa
Code Completion 4 Challenges

Complete the filecmp comparison code

Practise byte-accurate comparison, cmpfiles classification, dircmp results, and cache refresh.

Intermediate ~12 min read

Challenge 1

Compare the two files by their contents.

python Your answer
import filecmp
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    first = root / "first.txt"
    second = root / "second.txt"
    first.write_text("report", encoding="utf-8")
    second.write_text("report", encoding="utf-8")
    same = filecmp.cmp(first, second, )
    assert same is True
    print(same)

Press Ctrl⌘Enter to check your answer

Challenge 2

Separate matching files, differing files, and errors.

python Your answer
import filecmp
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    left, right = root / "left", root / "right"
    left.mkdir(); right.mkdir()
    (left / "same.txt").write_text("yes", encoding="utf-8")
    (right / "same.txt").write_text("yes", encoding="utf-8")
    (left / "diff.txt").write_text("one", encoding="utf-8")
    (right / "diff.txt").write_text("two", encoding="utf-8")
    matches, mismatches, errors = (left, right, ["same.txt", "diff.txt", "absent.txt"], shallow=False)
    assert matches == ["same.txt"]
    assert mismatches == ["diff.txt"]
    assert errors == ["absent.txt"]
    print(matches, mismatches, errors)

Press Ctrl⌘Enter to check your answer

Challenge 3

Build a full-content directory comparison and read its changed common filenames.

python Your answer
import filecmp
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    left, right = root / "left", root / "right"
    left.mkdir(); right.mkdir()
    (left / "settings.ini").write_text("mode=dev", encoding="utf-8")
    (right / "settings.ini").write_text("mode=prod", encoding="utf-8")
    comparison = filecmp.dircmp(left, right, shallow=False)
    changed = comparison.
    assert changed == ["settings.ini"]
    print(changed)

Press Ctrl⌘Enter to check your answer

Challenge 4

Clear cached comparison results after a rapid file update before checking the contents again.

python Your answer
import filecmp
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    first = Path(temporary) / "first.txt"
    second = Path(temporary) / "second.txt"
    first.write_text("new", encoding="utf-8")
    second.write_text("new", encoding="utf-8")
    filecmp.clear_cache()
    assert filecmp.cmp(first, second, shallow=False) is True
    first.write_text("old", encoding="utf-8")
    filecmp.
    assert filecmp.cmp(first, second, shallow=False) is False
    print("fresh comparison")

Press Ctrl⌘Enter to check your answer