filecmp Diffs Files And Directory Trees
Compare individual files and whole directory trees with filecmp, separating matches, mismatches, and files missing on one side.
Code
import filecmp
import tempfile
from pathlib import Path
def main() -> None:
with tempfile.TemporaryDirectory() as tmp:
left = Path(tmp) / 'left'
right = Path(tmp) / 'right'
left.mkdir()
right.mkdir()
(left / 'same.txt').write_text('shared content', encoding='utf-8')
(right / 'same.txt').write_text('shared content', encoding='utf-8')
(left / 'changed.txt').write_text('v1', encoding='utf-8')
(right / 'changed.txt').write_text('v2', encoding='utf-8')
(left / 'only-left.txt').write_text('left', encoding='utf-8')
(right / 'only-right.txt').write_text('right', encoding='utf-8')
print('single equal:', filecmp.cmp(left / 'same.txt', right / 'same.txt', shallow=False))
print('single differs:', filecmp.cmp(left / 'changed.txt', right / 'changed.txt', shallow=False))
match, mismatch, errors = filecmp.cmpfiles(
left,
right,
['same.txt', 'changed.txt', 'only-left.txt'],
shallow=False,
)
print('match:', match)
print('mismatch:', mismatch)
print('errors:', errors)
diff = filecmp.dircmp(left, right)
print('common:', diff.common)
print('left only:', diff.left_only)
print('right only:', diff.right_only)
print('differing:', diff.diff_files)
if __name__ == '__main__':
main()How it works
filecmp Diffs Files And Directory Trees reduces to the function main.
From filecmp it pulls Path — the imports name exactly which library surface the snippet touches.
What to watch for
- Plan for an install step:
filecmpis a real dependency, resolved by the package manager.
Putting it to use
The run emits 9 labeled sections — single equal:, single differs:, match:, mismatch:, errors:, common:, left only:, right only:, differing: — one per step.
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- Yes — `filecmp`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.