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

查看:186
本文介绍了如何使用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

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天全站免登陆