【问题标题】:Use Python to automate copying files to their corresponding target folders(shutil.copytree doesn't work as intended)使用 Python 自动将文件复制到其相应的目标文件夹(shutil.copytree 无法按预期工作)
【发布时间】:2015-12-05 01:33:29
【问题描述】:

我想自动化将文件(在其目标文件夹中)复制到位于计算机上不同目录中的相应源文件夹(与源文件夹结构相同)的过程...

我尝试使用python的shutil.copytree,但这会将所有目标文件夹复制到源文件夹中,并且Python文档说“由dst命名的目标目录必须不存在”(在我的情况下,打破规则)。所以我想要做的就是只将目标文件复制到相应的文件夹中,这样源文件和目标文件最终会留在同一个文件夹中......是否可以使用python来做?

在这里,我附上了一个截图,以进一步解释我的意思。

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

【问题讨论】:

  • 使用 shutil.copyfile() 一个一个地复制它们
  • 顺便说一句,您的术语有点混乱:我们通常将复制到目标(或目的地)。

标签: python file move shutil copytree


【解决方案1】:

这是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')

【讨论】:

    【解决方案2】:

    我刚刚找到了一个相当简单的方法来实现它。

    我们可以使用同上命令将 2 个文件夹合并在一起。

    ditto PlaceB PlaceA

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 2022-12-12
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2017-03-31
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多