Python Forum
Sutil.copytree, I'm getting File Exists.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sutil.copytree, I'm getting File Exists.
#1
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.
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  use of shutil.copytree with ENOTDIR exception yan 2 842 Nov-29-2023, 03:02 PM
Last Post: yan
  pathlib destpath.exists() true even file does not exist NaN 9 4,566 Dec-01-2020, 12:43 PM
Last Post: NaN
  Check if a file exists. Pedroski55 5 3,251 Sep-08-2020, 10:01 AM
Last Post: Pedroski55
  p]Why os.path.exists("abc/d") and os.path.exists("abc/D") treat same rajeev1729 1 2,140 May-27-2020, 08:34 AM
Last Post: DeaD_EyE
  Shutil move if file exists in destination Friend 2 6,651 Feb-02-2020, 01:45 PM
Last Post: Friend
  check if file exists. ian 6 8,332 Jul-15-2017, 09:34 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020