Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude some of subfolders while copying (im using copytree) in python

Tags:

python

I am trying to implement a DIR-COPY. my input is like this..

    source = D/Test/Source
    Target = D/Test/Target
    Ignore_Pattern = '*.exe'
    Exclude_Sub_Folder = D/Test/Source/Backup,D/Test/Source/Backup2

I am able ignore .exe files using ignore property in copytree Did like this

    shutil.copytree(source , Target ,ignore=shutil.ignore_patterns(Ignore_Pattern)) 

I am not sure how to exclude some of the subfolders in the source directory.

Please help.....

Thanks

like image 879
techrhl Avatar asked Mar 11 '15 11:03

techrhl


1 Answers

You can ignore all folders that have a name of Backup or Backup2:

shutil.copytree(source , Target ,ignore=shutil.ignore_patterns(Ignore_Pattern, "Backup", "Backup2"))

"But I have multiple folders named 'Backup' and I specifically want to ignore only the one in the Test/Source directory", you say. In that case, you need to provide a custom ignoring function that investigates the full path.

to_exclude = ["D:/Test/Source/Backup", "D:/Test/Source/Backup2"]

#ignores excluded directories and .exe files
def get_ignored(path, filenames):
    ret = []
    for filename in filenames:
        if os.path.join(path, filename) in to_exclude:
            ret.append(filename)
        elif filename.endswith(".exe"):
            ret.append(filename)
    return ret

shutil.copytree(source , Target ,ignore=get_ignored)

(Take care in to_exclude to use the correct path separator for your particular OS. You don't want "Test\Source\Backup" getting included because you used the wrong kind of slash.)

like image 186
Kevin Avatar answered Oct 18 '22 01:10

Kevin