如何使用 Python 将目录及其内容复制到现有位置? [英] How to copy a directory and its contents to an existing location using Python?

查看:18
本文介绍了如何使用 Python 将目录及其内容复制到现有位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将目录及其所有内容复制到已存在的路径中.问题是,在 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)

这篇关于如何使用 Python 将目录及其内容复制到现有位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆