python - recursive dircmp (compare two directories to ensure they have the same files and subdirectories) -
from observe filecmp.dircmp
recursive, inadequate needs, @ least in py2. want compare 2 directories , contained files. exist, or need build (using os.walk
, example). prefer pre-built, else has done unit-testing :)
the actual 'comparison' can sloppy (ignore permissions, example), if helps.
i boolean, , report_full_closure
printed report. goes down common subdirs. afiac, if have in left or right dir only different dirs. build using os.walk
instead.
here's alternative implementation of comparison function filecmp
module. uses recursion instead of os.walk
, little simpler. however, not recurse using common_dirs
, subdirs
attributes since in case implicitly using default "shallow" implementation of files comparison, not want. in implementation below, when comparing files same name, we're comparing contents.
import filecmp import os.path def are_dir_trees_equal(dir1, dir2): """ compare 2 directories recursively. files in each directory assumed equal if names , contents equal. @param dir1: first directory path @param dir2: second directory path @return: true if directory trees same , there no errors while accessing directories or files, false otherwise. """ dirs_cmp = filecmp.dircmp(dir1, dir2) if len(dirs_cmp.left_only)>0 or len(dirs_cmp.right_only)>0 or \ len(dirs_cmp.funny_files)>0: return false (_, mismatch, errors) = filecmp.cmpfiles( dir1, dir2, dirs_cmp.common_files, shallow=false) if len(mismatch)>0 or len(errors)>0: return false common_dir in dirs_cmp.common_dirs: new_dir1 = os.path.join(dir1, common_dir) new_dir2 = os.path.join(dir2, common_dir) if not are_dir_trees_equal(new_dir1, new_dir2): return false return true
Comments
Post a Comment