Recursively compare two directories to ensure they have the same files and subdirectories

后端 未结 11 1253
猫巷女王i
猫巷女王i 2020-12-23 20:49

From what I observe filecmp.dircmp is recursive, but inadequate for my needs, at least in py2. I want to compare two directories and all their contained files. Do

11条回答
  •  离开以前
    2020-12-23 21:48

    This will check if files are in the same locations and if their content is the same. It will not correctly validate for empty subfolders.

    import filecmp
    import glob
    import os
    
    path_1 = '.'
    path_2 = '.'
    
    def folders_equal(f1, f2):
        file_pairs = list(zip(
            [x for x in glob.iglob(os.path.join(f1, '**'), recursive=True) if os.path.isfile(x)],
            [x for x in glob.iglob(os.path.join(f2, '**'), recursive=True) if os.path.isfile(x)]
        ))
    
        locations_equal = any([os.path.relpath(x, f1) == os.path.relpath(y, f2) for x, y in file_pairs])
        files_equal = all([filecmp.cmp(*x) for x in file_pairs]) 
    
        return locations_equal and files_equal
    
    folders_equal(path_1, path_2)
    

提交回复
热议问题