Skip to main content
 首页 » 编程设计

python之python shutil.copytree() 的忽略回调不接受完整路径

2024年11月01日15birdshome

我想在调用 shutil.copytree() 时指定可忽略文件和目录的完整路径。有点像

def my_ignore(dir, files): 
 
    # return ["exclude.file"] # working 
 
    return ["/full_path_to/exclude.file"] # Not working 
 
shutil.copytree(src, dest, ignore=my_ignore) 

在此之后,排除的文件仍然存在,除非我只返回文件名而不是完整路径。问题是我真的想设置一个特定的文件而不是不同目录下的所有匹配文件名。

我在这里提到了一些问题,例如: How to write a call back function for ignore in shutil.copytree

Filter directory when using shutil.copytree?

但是没有一个答案有效。看起来 ignore hook 只能返回一个 glob-style,任何构造的完整路径都不起作用。

我错过了什么吗?

请您参考如下方法:

ignore 事实上必须只返回被忽略的文件名。但是,每次访问目录 shutil.copytree() 时都会调用该函数;您可以按目录 忽略文件。

如果您有需要忽略的文件的完整路径,则匹配传递给ignore 函数的第一个参数;它是该目录的完整路径:

def my_ignore(dir, files): 
    if dir == '/full_path_to': 
        return {"exclude.file"} 

我在这里还了一套;集合成员测试比列表更快。

如果您有一组要忽略的预定义路径,请将它们解析到字典中;键是目录路径,值是该路径中的文件名集:

from collections import defaultdict 
 
to_ignore = defaultdict(set) 
for path in ignored_paths: 
    dirname, filename = os.path.split(path) 
    to_ignore[dirname].add(filename) 
 
def my_ignore(src, files): 
    return to_ignore.get(src, set())