How to copy directory recursively in python and overwrite all?(如何在python中递归复制目录并覆盖全部?)
问题描述
我正在尝试将 /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 个只是 src
、dst
和 update
,如果是,如何(我是 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
.它工作得很好,你不必传递每个参数,只有 src
和 dst
是强制性的.
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.
这篇关于如何在python中递归复制目录并覆盖全部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在python中递归复制目录并覆盖全部?


基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01