python - 使用Python自动将文件复制到相应的目标文件夹(shutil.copytree无法按预期工作)

标签 python file move shutil copytree

我想自动将文件(在目标文件夹中)复制到位于计算机上不同目录中的相应源文件夹(与源具有相同的文件夹结构)的过程...
< br/>这里我在问题中附上了一张截图,以进一步解释我的意思。

非常感谢您的帮助!同时,我也会尝试对此进行更多研究!

enter image description here

最佳答案

这是 shutil.copytree 的修改版本,它不会创建目录(删除了 os.makedirs 调用)。

import os
from shutil import Error, WindowsError, copy2, copystat

def copytree(src, dst, symlinks=False, ignore=None):
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    # os.makedirs(dst)
    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:
                # Will raise a SpecialFileError for unsupported file types
                copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, why:
            errors.append((srcname, dstname, str(why)))
    try:
        copystat(src, dst)
    except OSError, why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.append((src, dst, str(why)))
    if errors:
        raise Error, errors

使用mock (或 Python 3.x 中的 unittest.mock),您可以通过将 os.makedirs 替换为 Mock 对象来临时禁用 os.makedirs (请参阅 unittest.mock.patch ):

from shutil import copytree
import mock  # import unittest.mock as mock   in Python 3.x

with mock.patch('os.makedirs'):
    copytree('PlaceB', 'PlaceA')

关于python - 使用Python自动将文件复制到相应的目标文件夹(shutil.copytree无法按预期工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34100242/

相关文章:

c - 在 C 中 move 实现

python - 是否可以在 Windows 上安装 wkhtmltopdf Python 包?

python - 如何在python中将double保存到文件?

objective-c - iOS : I can't write my file

java - 带空行的缓冲阅读器 readLine()

linux - 从 Linux 列表中 move (或复制)文件

rust - 为什么通过 `for` 循环迭代集合在 Rust 中被认为是 "move"?

python - 当包含有意义的空格时,如何编写与 re.VERBOSE 一起使用的模式?

python - 我应该了解 Python 哪些知识才能识别不同源文件中的注释?

python - 属性错误: module 'wikipedia' has no attribute 'summary'