python filecmp.dircmp ignore wildcard

Viewed 931

filecmp.dircmp is used to compare two folders. It accepts a parameter ignore yet it only does exact match not a wildcard match. Any idea how to ignore a pattern?

1 Answers

You can use the glob https://docs.python.org/3/library/glob.html to expand the pattern and feed the expanded list to the ignore parameter.

Lets say you have folder left and folder right and you want to filter out all *.foo and *.bar from comparison then,

import os
import glob
import filecmp

ignore_list = []
patterns_to_ignore = ['*.foo', '*.bar']
for pattern in patterns_to_ignore:
    ignore_left = [os.path.split(expanded)[1] for expanded in glob.glob(os.path.join(left, pattern))]
    ignore_right = [os.path.split(expanded)[1] for expanded in glob.glob(os.path.join(right, pattern))]
    ignore_list.extend(ignore_left)
    ignore_list.extend(ignore_right)


diff = filecmp.dircmp(left, right, ignore=ignore_list)
Related