问题描述
我正在尝试将目录及其所有内容复制到已存在的路径中.问题是,在 os 模块和 shutil 模块之间,似乎没有办法做到这一点.shutil.copytree() 函数预期目标路径事先不存在.
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.
推荐答案
distutils.dir_util.copy_tree 做你想做的事.
distutils.dir_util.copy_tree does what you want.
将整个目录树 src 复制到新地点 dst.src 和 dst必须是目录名称.如果 src 不是一个目录,引发 distutilsfileerror.如果 dst 不存在,则创建它使用 mkpath().的最终结果复制是 src 中的每个文件都是复制到 dst 和目录下src 被递归复制到 dst.返回之前的文件列表复制或可能已复制,使用他们的输出名称.回报值不受更新或dry_run:它只是所有的列表src 下的文件,名称为改为在dst下.
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)