arjunurs
arjunurs

Reputation: 1182

Creating a flat list from return values of a recursive python function

I am trying to compare two directories using the dircmp function in python

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))

I am trying to get a result like:

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

What is the best way to do this?

Upvotes: 1

Views: 259

Answers (1)

Eric Hulser
Eric Hulser

Reputation: 4022

Never used dircmp before...but I think this should work looking at your code...

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)

Upvotes: 1

Related Questions