Copy directory contents into a directory with python

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".

Asked By: prosseek

||

Answers:

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:

Answered By: prosseek

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/

Answered By: ikudyk

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("%sn" % 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('..')
Answered By: kutenzo
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.

Answered By: Bowen Xu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.