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

后端 未结 11 1309
猫巷女王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:53

    Another solution to Compare the lay out of dir1 and dir2, ignore the content of files

    See gist here: https://gist.github.com/4164344

    Edit: here's the code, in case the gist gets lost for some reason:

    import os
    
    def compare_dir_layout(dir1, dir2):
        def _compare_dir_layout(dir1, dir2):
            for (dirpath, dirnames, filenames) in os.walk(dir1):
                for filename in filenames:
                    relative_path = dirpath.replace(dir1, "")
                    if os.path.exists( dir2 + relative_path + '\\' +  filename) == False:
                        print relative_path, filename
            return
    
        print 'files in "' + dir1 + '" but not in "' + dir2 +'"'
        _compare_dir_layout(dir1, dir2)
        print 'files in "' + dir2 + '" but not in "' + dir1 +'"'
        _compare_dir_layout(dir2, dir1)
    
    
    compare_dir_layout('xxx', 'yyy')
    

提交回复
热议问题