Dan
Dan

Reputation: 5

find match folders then copy files and subfolders

Am new in Python and would like to do a task... I need to compare folder names from two folders dirfolder1 and dirfolder2... compare the folders in them and if they match...copy files and sub folders inside that matched folder...

thanks for your help.

Daddih.

Upvotes: 0

Views: 2096

Answers (1)

aravenel
aravenel

Reputation: 348

You could do something like the following:

import os, shutil

dir1 = r'/path/to/dir/1'
dir2 = r'/path/to/dir/2'
copy_dest = r'/path/to/copy/dirs/to'

dir1_folders = [dir for dir in os.listdir(dir1) if os.path.isdir(os.path.join(dir1, dir))]
dir2_folders = [dir for dir in os.listdir(dir2) if os.path.isdir(os.path.join(dir2, dir))]

for dir in dir1_folders:
    if dir in dir2_folders:
        shutil.copytree(os.path.join(dir1, dir), os.path.join(copy_dest, dir))

Basically, walk through each directory creating a list of its subdirectories, compare them, and for the matches, copy them (using copytree in case there are any subdirectories) into a third location.

Upvotes: 1

Related Questions