Recursively copy files to a subdirectory

I need to copy all files and folders to the current folder in a subdirectory. What would be the best way to do this? I tried the following snippet, but it fails because it does not work 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 better and easier. How to do it?

+3
source share
5 answers

I would never do this in python, but the following solution came to mind. It does not look simple, but it should work and can be simplified (not verified, sorry, now there is no access to the computer):

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)
+2
source
+1

mamnun,

os, cp -r, , , .

+1

python? shutil . OS, cp linux xcopy Windows?

python

import os

os.system("cp file1 file2")

, .

0

python, , :)

def copy_all(fr, to, overwrite=True):
  fr = os.path.normpath(fr)
  to = os.path.normpath(to)

  if os.path.isdir(fr):
    if (not os.path.exists(to + os.path.basename(fr)) and not
    os.path.basename(fr) == os.path.basename(to)):
      to += "/" + os.path.basename(fr)
      mkdirs(to)
    for file in os.listdir(fr):
      copy_all(fr + "/" + file, to + "/")
  else: #symlink or file
    dest = to
    if os.path.isdir(to):
      dest += "/"
      dest += os.path.basename(fr)

    if overwrite and (os.path.exists(dest) or os.path.islink(dest)
      rm(dest)

    if os.path.isfile(fr):
      shutil.copy2(fr, dest)
    else: #has to be a symlink
      os.symlink(os.readlink(fr), dest)  


def mkdirs(path):                                                 
  if not os.path.isdir(path):
    os.makedirs(path)


def rm(path):                                                     
  if os.path.isfile(path) or os.path.islink(path):
    os.remove(path)
  elif os.path.isdir(path):
    for file in os.listdir(path):
      fullpath = path+"/"+file
      os.rmdir(fullpath)
0

Source: https://habr.com/ru/post/1777908/


All Articles