首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >(distutil + shutil) * copytree =?

(distutil + shutil) * copytree =?
EN

Stack Overflow用户
提问于 2011-09-25 19:47:36
回答 4查看 3.7K关注 0票数 7

我想要shutil的复制树函数提供的忽略模式。我希望src树替换目标目录中的所有现有文件/文件夹,比如distutil.dir_util.copy_tree。

我是一个相当新的Python用户,似乎找不到任何关于这方面的帖子。

EN

回答 4

Stack Overflow用户

发布于 2011-09-26 11:34:02

我早些时候想说这个,但是我没有。http://docs.python.org/library/shutil.html有一个版本的复制树函数。我查看了一下它,看看它是否只会替换现有的文件,从我所能断定的情况来看,它会覆盖现有的文件,但如果有任何目录已经存在,它就会失败。如果目录已经存在,则会导致os.mkdirs失败。

所需的导入:

代码语言:javascript
复制
import os
import os.path
import shutil

http://code.activestate.com/recipes/82465-a-friendly-mkdir/获取_mkdir (那里的一个评论者提到os.mkdirs具有大多数相同的行为,但没有注意到如果要创建的任何目录已经存在,_mkdir不会失败)

代码语言:javascript
复制
def _mkdir(newdir):
    """works the way a good mkdir should :)
        - already exists, silently complete
        - regular file in the way, raise an exception
        - parent directory(ies) does not exist, make them as well
    """
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            _mkdir(head)
        #print "_mkdir %s" % repr(newdir)
        if tail:
            os.mkdir(newdir)

虽然它不需要像os.mkdirs这样的mode参数,但copytree不使用它,所以不需要它。

然后将copytree更改为调用_mkdir而不是os.mkdirs

代码语言:javascript
复制
def copytree(src, dst, symlinks=False):
    """Recursively copy a directory tree using copy2().

    The destination directory must not already exist.
    If exception(s) occur, an Error is raised with a list of reasons.

    If the optional symlinks flag is true, symbolic links in the
    source tree result in symbolic links in the destination tree; if
    it is false, the contents of the files pointed to by symbolic
    links are copied.

    XXX Consider this example code rather than the ultimate tool.

    """
    names = os.listdir(src)
    # os.makedirs(dst)
    _mkdir(dst) # XXX
    errors = []
    for name in names:
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks)
            else:
                shutil.copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except (IOError, os.error), why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
    try:
        shutil.copystat(src, dst)
    except WindowsError:
        # can't copy file access times on Windows
        pass
票数 3
EN

Stack Overflow用户

发布于 2013-10-29 03:44:04

只需扩展Dan的答案,合并ignore参数并将shutil添加到'Error‘类(适用于copytree):

代码语言:javascript
复制
def copytree(src, dst, symlinks=False, ignore=None):
    """Recursively copy a directory tree using copy2().

    The destination directory must not already exist.
    If exception(s) occur, an Error is raised with a list of reasons.

    If the optional symlinks flag is true, symbolic links in the
    source tree result in symbolic links in the destination tree; if
    it is false, the contents of the files pointed to by symbolic
    links are copied.

    XXX Consider this example code rather than the ultimate tool.

    """
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    _mkdir(dst) # XXX
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                shutil.copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except (IOError, os.error), why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except shutil.Error, err:
            errors.extend(err.args[0])
    try:
        shutil.copystat(src, dst)
    except WindowsError:
        # can't copy file access times on Windows
        pass
票数 1
EN

Stack Overflow用户

发布于 2015-05-11 22:21:54

这是一个同时使用distutils和shutil的变通方法:

代码语言:javascript
复制
ignorePatterns=('.git')
shutil.copytree(src, "__TMP__", ignore=shutil.ignore_patterns(ignorePatterns))
distutils.dir_util.copy_tree("__TMP__", dest)
distutils.dir_util.remove_tree("__TMP__")

注意:这不是一种有效的方法,因为它将相同的文件复制两次。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7545299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档