something similar to shutil.copytree that can overwrite?

Justin Ezequiel justin.mailinglists at gmail.com
Wed Jun 20 06:40:06 EDT 2007


On Jun 20, 5:30 pm, Ben Sizer <kylo... at gmail.com> wrote:
> I need to copy directories from one place to another, but it needs to
> overwrite individual files and directories rather than just exiting if
> a destination file already exists.

What version of Python do you have?
Nothing in the source would make it exit if a target file exists.
(Unless perhaps you have sym-links or the like.)

Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]

copytree calls copy2 which calls copyfile

from shutil.py:
#--------------------------------------------------------------------
def _samefile(src, dst):
    # Macintosh, Unix.
    if hasattr(os.path,'samefile'):
        try:
            return os.path.samefile(src, dst)
        except OSError:
            return False

    # All other platforms: check for same pathname.
    return (os.path.normcase(os.path.abspath(src)) ==
            os.path.normcase(os.path.abspath(dst)))

def copyfile(src, dst):
    """Copy data from src to dst"""
    if _samefile(src, dst):
        raise Error, "`%s` and `%s` are the same file" % (src, dst)

    fsrc = None
    fdst = None
    try:
        fsrc = open(src, 'rb')
        fdst = open(dst, 'wb')
        copyfileobj(fsrc, fdst)
    finally:
        if fdst:
            fdst.close()
        if fsrc:
            fsrc.close()
#--------------------------------------------------------------------





More information about the Python-list mailing list