2009-02-04 82 views
32

我试图将目录及其所有内容复制到已存在的路径。问题是,在os模块和shutil模块之间,似乎没有办法做到这一点。 shutil.copytree()函数预期目标路径不存在。如何使用Python将目录及其内容复制到现有位置?

我正在寻找的确切结果是将整个文件夹结构复制到另一个文件结构上,在发现的任何重复项上无声覆盖。在我加入并开始编写自己的函数来完成此操作之前,我想我会询问是否有人知道现有的配方或片段是否可以实现此目的。

回答

42

distutils.dir_util.copy_tree你想要做什么。

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.

(在上述网址的更多文档)

+1

以前没见过这个,很好找。我唯一需要注意的是它没有指出哪些文件被覆盖,哪些文件是重新创建的。然而,只要这不是要求,这看起来很完美。 – 2009-02-04 17:29:57

+0

这是一个不错的选择,虽然它需要安装distutils。没有这么大的问题,因为我们使用pyinstaller将它捆绑到EXE中。 – Soviut 2009-02-04 18:15:56

0

为什么不自己实施它使用os.walk

+5

这就是我正在考虑,但我想确保我没有重新发明轮子。 – Soviut 2009-02-04 18:15:08

0

对于高级别文件操作一样,使用shutil模块和你的情况copytree功能。我认为这比“滥用”失误更清洁。

更新::忘记了答案,我忽略了OP做的尝试shutil。

0

你是否在得到“无法创建目录时,它已经存在”的错误? 我不知道有多少愚蠢的是这一点,但我所做的就是为一条直线插入copytree模块: 我改变:

def copytree(src, dst, symlinks=False): 
    names = os.listdir(src) 
    os.makedirs(dst) 

到:

def copytree(src, dst, symlinks=False): 
    names = os.listdir(src) 
    if (os.path.isdir(dst)==False): 
     os.makedirs(dst)  

我想我做了一些bluder。如果是这样,有人可以指出我吗?对不起,我是很新的蟒蛇:P

相关问题