Skip to content
Advertisement

How to copy directory recursively in python and overwrite all?

I’m trying to copy /home/myUser/dir1/ and all its contents (and their contents, etc.) to /home/myuser/dir2/ in python. Furthermore, I want the copy to overwrite everything in dir2/.

It looks like distutils.dir_util.copy_tree might be the right tool for the job, but not sure if there’s anything easier/more obvious to use for such a simple task.

If it is the right tool, how do I use it? According to the docs there are 8 parameters that it takes. Do I have to pass all 8 are just src, dst and update, and if so, how (I’m brand new to Python).

If there’s something out there that’s better, can someone give me an example and point me in the right direction?

Advertisement

Answer

Notice:

distutils has been deprecated and will be removed in Python 3.12. Consider looking for other answers at this question if you are looking for a post-3.12 solution.


Original answer:

You can use distutils.dir_util.copy_tree. It works just fine and you don’t have to pass every argument, only src and dst are mandatory.

However in your case you can’t use a similar tool likeshutil.copytree because it behaves differently: as the destination directory must not exist this function can’t be used for overwriting its contents.

If you want to use the cp tool as suggested in the question comments beware that using the subprocess module is currently the recommended way for spawning new processes as you can see in the documentation of the os.system function.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement