something similar to shutil.copytree that can overwrite?

John J. Lee jjl at pobox.com
Tue Jun 26 23:54:32 CEST 2007


Ben Sizer <kylotan at gmail.com> writes:

> On 20 Jun, 11:40, Justin Ezequiel <justin.mailingli... at gmail.com>
> wrote:
>> 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.)
>
> I have 2.5, and I believe the behaviour I saw was that it exits if a
> directory already exists and it skips any files that already exist. It
> certainly wouldn't overwrite anything.

How about distutils.dir_util.copy_tree?  It's a documented API:

http://docs.python.org/dist/module-distutils.dirutil.html


Here's a demo.  Note the arguments to distutils.dir_util.copy_tree
have a different meaning to shutil.copytree IIRC (you need to pass the
parent of the directory rather than the directory itself):


from distutils.dir_util import copy_tree
import os

def mkdir(dirname):
    os.mkdir(dirname)

def write(filename, data):
    f = open(filename, "w")
    try:
        f.write(data)
    finally:
        f.close()

def read(filename):
    f = open(filename)
    try:
        return f.read()
    finally:
        f.close()

def make_tree_1():
    mkdir("1")
    mkdir(os.path.join("1", "1"))
    write(os.path.join("1", "1", "a"), "abc")
    return "1"

def make_tree_2():
    mkdir("2")
    mkdir(os.path.join("2", "1"))
    write(os.path.join("2", "1", "a"), "bcd")
    return "2"

dirname_1 = make_tree_1()
dirname_2 = make_tree_2()
copy_tree(dirname_1, dirname_2)
result = read(os.path.join(dirname_2, "1", "a"))
assert result == "abc", result



John



More information about the Python-list mailing list