Python Forum

Full Version: Sutil.copytree, I'm getting File Exists.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a folder 'target' with other folders that have folders called 'env'. I am trying to copy all files/directories from 'target' to 'backup_folder' without 'env'.

#!/usr/bin/env python3.8
import glob
import platform
import os, shutil
import errno

def copytree(src, dst, symlinks=False, ignore=None):

    try:
        if os.path.exists(dst):
            shutil.rmtree(dst)
            print('remove and create')

        for root, dir, file in os.walk(src):
            if root.split('/')[-1] != 'env':
                s = os.path.join(src, root)
                d = os.path.join(dst, root)
                if os.path.isdir(root):
                    print(d)
                    shutil.copytree(root, d, symlinks, ignore)
                else:
                    shutil.copy2(root, d)

    except OSError as error:
        if error.errno == errno.ENOTDIR:
            shutil.copy(source_dir_promp, destinations_dir_prompt)
        else:
            print('Directory not copied. Error: {}'.format(error))
        raise SystemExit


copytree('target', 'backup_folder')
I really cannot figure it out how to resolve it.
I think you could simply use the 'ignore' parameter in shutil.copytree() instead of redefining your own version of copytree()
def ignore_func(src, names):
    return ['env'] if 'env' in names else []

shutil.copytree('target', 'backup_folder', ignore=ignore_func)