pythondirectorysymlinkcopytree

copytree(), What are parameters symlink and ignore for?


I am quite new to Python, so please bear with me. I was looking to write something to copy files from one directory to another. I found the following Question and Answers: Here

There, I found this answer:

def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
    s = os.path.join(src, item)
    d = os.path.join(dst, item)
    if os.path.isdir(s):
        shutil.copytree(s, d, symlinks, ignore)
    else:
        shutil.copy2(s, d)

Which someone later added to in order to resolve some issues with it:

#!/usr/bin/python
import os
import shutil
import stat
def copytree(src, dst, symlinks = False, ignore = None):
  if not os.path.exists(dst):
    os.makedirs(dst)
    shutil.copystat(src, dst)
  lst = os.listdir(src)
  if ignore:
    excl = ignore(src, lst)
    lst = [x for x in lst if x not in excl]
  for item in lst:
    s = os.path.join(src, item)
    d = os.path.join(dst, item)
    if symlinks and os.path.islink(s):
      if os.path.lexists(d):
        os.remove(d)
      os.symlink(os.readlink(s), d)
      try:
        st = os.lstat(s)
        mode = stat.S_IMODE(st.st_mode)
        os.lchmod(d, mode)
      except:
        pass # lchmod not available
    elif os.path.isdir(s):
      copytree(s, d, symlinks, ignore)
    else:
      shutil.copy2(s, d)

I understood that shutil.copytree() had issues when the destination directory already existed and these revisions were meant to deal with it.

My question is about the symlinks and the ignore parameters that I'm seeing and not understanding what they do and how it resolves the issue.

I was able to find the definitions below, which went way over my head:

symlinks (optional) : This parameter accepts True or False, depending on which the metadata of the original links or linked links will be copied to the new tree.

ignore (optional) : If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree(), and a list of its contents, as returned by os.listdir().


Solution

  • This might not be what you are looking for, but if you are able it would be way easier to code and understand to simply use your os's copy function. This can be done from python whith the os library.

    def copytree(src,dst):
        os.system("cp -r "+src+" "+dst)
    

    This example assumes you're using linux but it would work on any OS you would just have to switch 'cp -r' out for your local copy command.