Question

I have a directory /a/b/c that has files and subdirectories. I need to copy the /a/b/c/* in the /x/y/z directory. What python methods can I use?

I tried shutil.copytree("a/b/c", "/x/y/z"), but python tries to create /x/y/z and raises an error "Directory exists".

Was it helpful?

Solution

I found this code working which is part of the standard library:

from distutils.dir_util import copy_tree

# copy subdirectory example
from_directory = "/a/b/c"
to_directory = "/x/y/z"

copy_tree(from_directory, to_directory)

Reference:

OTHER TIPS

You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths

glob2 link: https://code.activestate.com/pypm/glob2/

from subprocess import call

def cp_dir(source, target):
    call(['cp', '-a', source, target]) # Linux

cp_dir('/a/b/c/', '/x/y/z/')

It works for me. Basically, it executes shell command cp.

The python libs are obsolete with this function. I've done one that works correctly:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top