views:

3859

answers:

4

I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the shutil.copytree() function expects that the destination path not exist beforehand.

The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this.

A: 

Why not implement it on your own using os.walk?

Swaroop C H
that's what I was considering, but I wanted to make sure I wasn't reinventing the wheel.
Soviut
+10  A: 

distutils.dir_util.copy_tree does what you want.

Copy an entire directory tree src to a new location dst. Both src and dst must be directory names. If src is not a directory, raise DistutilsFileError. If dst does not exist, it is created with mkpath(). The end result of the copy is that every file in src is copied to dst, and directories under src are recursively copied to dst. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by update or dry_run: it is simply the list of all files under src, with the names changed to be under dst.

(more documentation at the above url)

Ali A
Haven't seen this one before, good find. My only caveat is that it gives no indication which files were overwritten and which were created anew. As long as that isn't a requirement, however, this looks perfect.
Ben Blank
This is a good one, although it'll require that distutils is installed. Not such a big issue since we're bundling this up into an EXE with pyinstaller anyways.
Soviut
distutils is part of the standard library, so should, in theory always be installed.
Ali A
+2  A: 

For highlevel file operations like that use the shutil module and in your case the copytree function. I think that is cleaner than "abusing" distutils.

UPDATE:: Forget the answer, I overlooked that the OP did try shutil.

André
I mentioned in my question that shutil.copytree() is what i was trying to use but not fitting the bill.
Soviut
I would normally agree with this, but it doesn't quite do what the O.P. asked for.
Ali A
You guys are right, I overlooked that in the question, was too late that evening :-)
André
A: 

Are you gettting the error that says "Cannot create a directory when its already present"? I am not sure how much silly is this, but all i did was to insert a single line into copytree module: I changed : def copytree(src, dst, symlinks=False): names = os.listdir(src) os.makedirs(dst)

into: def copytree(src, dst, symlinks=False): names = os.listdir(src) if (os.path.isdir(dst)==False): os.makedirs(dst)

I guess i did some bluder. If so, could someone point me out that? Sorry, i am very new to python :P