Skip to main content
 首页 » 编程设计

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

2024年10月24日12虾米姐

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

我尝试使用 python 的 shutil.copytree,但这会将所有目标文件夹复制到源文件夹中,Python 文档说“目标目录,由 dst 命名,必须不存在”(在我的例子中,打破规则)。所以我想做的是只将目标文件复制到相应的文件夹中,这样源文件和目标文件最终就会留在同一个文件夹中......是否可以使用 python 来实现?
< br/>这里我附上问题的截图来进一步解释我的意思。

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

请您参考如下方法:

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