我正在尝试使用python中的dircmp函数比较两个目录

def cmpdirs(dir_cmp):
    for sub_dcmp in dir_cmp.subdirs.values():
        cmpdirs(sub_dcmp)
    return dir_cmp.left_only, dir_cmp.right_only, dir_cmp.common_files

if __name__ == '__main__':
    dcmp = dircmp('dir1', 'dir2')
    result = list(cmpdirs(dcmp))


我试图得到这样的结果:

([file1,file2],[file3,file4],[file5,file6])


做这个的最好方式是什么?

最佳答案

以前从未使用过dircmp ...但是我认为这应该可以在查看您的代码时使用...

def cmpdirs(dir_cmp):
    # make copies of the comparison results
    left   = dir_cmp.left_only[:]
    right  = dir_cmp.righ_only[:]
    common = dir_cmp.common_files[:]

    for sub_dcmp in dir_cmp.subdirs.values():
        sub_left, sub_right, sub_common = cmpdirs(sub_dcmp)

        # join the childrens results
        left   += sub_left
        right  += sub_right
        common += sub_common

    # return the merged results
    return (left, right, common)

if __name__ == '__main__':
    dcmp   = dircmp('dir1', 'dir2')
    result = cmpdirs(dcmp)

关于python - 根据递归python函数的返回值创建平面列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11996735/

10-09 05:35