I have a directory, 'Dst Directory', which has files and folders in it and I have 'src Directory' which also has files and folders in it. What I want to do is move the contents of 'src Directory' to 'Dst Directory' and overwrite anyfiles that exist with the same name. So for example 'Src Directory\file.txt' needs to be moved to 'Dst Directory\' and overwrite the existing file.txt. The same applies for some folders, moving a folder and merging the contents with the same folder in 'dst directory'
I'm currently using shutil.move to move the contents of src to dst but it won't do it if the files already exist and it won't merge folders; it'll just put the folder inside the existing folder.
Update: To make things a bit clearer; What I'm doing is unzipping an archive to the Dst Directory and then moving the contents of Src Directory there and rezipping, effectively updating files in the zip archive. This will be repeated for adding new files or new versions of files etc which is why it needs to overwrite and merge
Solved: I solved my problem by using distutils.dir_util.copy_tree(src, dst), this copies the folders and files from src directory to dst directory and overwrites/merges where neccesary. Hope that helps some people!
Hope that makes sense, thanks!
If you also need to overwrite files with read only flag use this:
Use
copy()
instead, which is willing to overwrite destination files. If you then want the first tree to go away, justrmtree()
it separately once you are done iterating over it.http://docs.python.org/library/shutil.html#shutil.copy
http://docs.python.org/library/shutil.html#shutil.rmtree
Update:
Do an
os.walk()
over the source tree. For each directory, check if it exists on the destination side, andos.makedirs()
it if it is missing. For each file, simplyshutil.copy()
and the file will be created or overwritten, whichever is appropriate.I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.
I solved it by using
os.walk()
, recursively calling my function and usingshutil.move()
on files which I wanted to overwrite and folders which did not exist.It works like
shutil.move()
, but with the benefit that existing files are only overwritten, but not deleted.Have a look at:
os.remove
to remove existing files.This will go through the source directory, create any directories that do not already exist in destination directory, and move files from source to the destination directory:
Any pre-existing files will be removed first (via
os.remove
) before being replace by the corresponding source file. Any files or directories that already exist in the destination but not in the source will remain untouched.Since none of the above worked for me, so I wrote my own recursive function. Call Function copyTree(dir1, dir2) to merge directories. Run on multi-platforms Linux and Windows.