recursive copy in a directory tree?

Fredrik Lundh fredrik at pythonware.com
Thu Oct 14 02:58:05 EDT 1999


yinger <ayinger1 at my-deja.com> wrote:
>   I am looking for a python util that *recursively* copies files from a
> source directory tree to a target with wildcard syntax.
> 
>   In other words, something like
> 
>      recurcopy('source','target','*.html')
> 
> that would copy all html files in the source directory tree to the
> target directory tree (creating any missing directories in the target
> as it goes along).
> 
>   I have to use something that is relatively platform independent, so
> I'm stuck with using the os, shutil, and glob modules.

you forgot about "find":

# from http://www.pythonware.com/people/fredrik/librarybook.htm

import errno, find, os, shutil

SOURCE = "./samples"
TARGET = "/tmp"

PATTERN = "*.txt"

source = os.path.normpath(SOURCE)

for file in find.find(PATTERN, source):
    target = TARGET + os.path.normpath(file)[len(source):]
    try:
        print file, "..."
        shutil.copyfile(file, target)
    except IOError, (errcode, message):
        if errcode == errno.ENOENT:
            # create directory and try again
            os.makedirs(os.path.dirname(target))
            shutil.copyfile(file, target)
        else:
            raise

</F>

coming soon:
http://www.pythonware.com/people/fredrik/librarybook.htm





More information about the Python-list mailing list