Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a directory and its contents to an existing location using Python?

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.

like image 824
Soviut Avatar asked Feb 04 '09 16:02

Soviut


People also ask

How do I copy an entire directory to a destination folder?

Alternatively, right-click the folder, select Show more options and then Copy. In Windows 10 and earlier versions, right-click the folder and select Copy, or click Edit and then Copy. Navigate to the location where you want to place the folder and all its contents.

How do you copy the contents of a directory to another?

Copying Directories with cp Command To copy a directory, including all its files and subdirectories, use the -R or -r option.


1 Answers

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)

like image 106
Ali Afshar Avatar answered Oct 05 '22 03:10

Ali Afshar