如何在python中递归复制目录并覆盖全部?

2022-01-20 00:00:00 python 复制 distutils

问题描述

我正在尝试将 /home/myUser/dir1/ 及其所有内容(及其内容等)复制到 /home/myuser/dir2/在蟒蛇.此外,我希望副本覆盖 dir2/ 中的所有内容.

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/.

它看起来像 distutils.dir_util.copy_tree 可能是适合这项工作的工具,但不确定是否有任何更容易/更明显的工具用于如此简单任务.

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.

如果它是正确的工具,我该如何使用它?根据 docs 有 8 个参数.我是否必须通过所有 8 个只是 srcdstupdate,如果是,如何(我是 Python 新手).

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? Thanks in advance!


解决方案

你可以使用 distutils.dir_util.copy_tree.它工作得很好,你不必传递每个参数,只有 srcdst 是强制性的.

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.

但是,在您的情况下,您不能使用像 shutil.copytree 这样的类似工具,因为它的行为不同:由于目标目录不能存在,因此该函数不能用于覆盖其内容.

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.

如果您想按照问题评论中的建议使用 cp 工具,请注意使用 subprocess 模块目前是生成新进程的推荐方式,如您所见在 os.system 函数的文档中.

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.

相关文章