Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive file copying into subdirectory

Tags:

python

I need to copy all the files and folders to the current folder to a subdirectory. What would be the best way to do so? I tried the following snippet but it fails as it fails if the destination directory already exists.

def copy(d=os.path.curdir):
    dest = "t"
    for i in os.listdir(d):
        if os.path.isdir(i):
            shutil.copytree(i, dest)
        else:
            shutil.copy(i, dest)

I have the feeling that the same task can be done in a better and easier manner. How do i do it?


2 Answers

I would never do it on python, but the following solution came to mind. It doesn't look simple, but it should work and can be simplified (haven't checked, sorry, no access to the computer now):

def copyDirectoryTree(directory, destination, preserveSymlinks=True):
  for entry in os.listdir(directory):
    entryPath = os.path.join(directory, entry)
    if os.path.isdir(entryPath):
      entrydest = os.path.join(destination, entry)
      if os.path.exists(entrydest):
        if not os.path.isdir(entrydest):
          raise IOError("Failed to copy thee, the destination for the `" + entryPath + "' directory exists and is not a directory")
        copyDirectoryTree(entrypath, entrydest, preserveSymlinks)
      else:
        shutil.copytree(entrypath, entrydest, preserveSymlinks)
    else: #symlinks and files
      if preserveSymlinks:
        shutil.copy(entryPath, directory)
      else:
        shutil.copy(os.path.realpath(entryPath), directory)
like image 104
khachik Avatar answered May 09 '26 03:05

khachik


See the code in http://docs.python.org/library/shutil.html, then tweak it a little (e.g. try: around os.makedirs(dst)).

like image 35
Ofir Avatar answered May 09 '26 02:05

Ofir