Gol*_*les 11 python shutil copytree
有没有办法可以使用绝对路径过滤目录?
shutil.copytree(directory,
target_dir,
ignore = shutil.ignore_patterns("/Full/Path/To/aDir/Common"))
Run Code Online (Sandbox Code Playgroud)
当尝试过滤位于" aDir" 下的"公共"目录时,这似乎不起作用.如果我这样做:
shutil.copytree(directory,
target_dir,
ignore = shutil.ignore_patterns("Common"))
Run Code Online (Sandbox Code Playgroud)
它可以工作,但每个名为Common的目录都将在"树"中进行过滤,这不是我想要的.
有什么建议 ?
谢谢.
phi*_*hag 13
您可以创建自己的忽略功能:
shutil.copytree('/Full/Path', 'target',
ignore=lambda directory, contents: ['Common'] if directory == '/Full/Path/To/aDir' else [])
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望能够copytree使用相对路径调用:
import os.path
def ignorePath(path):
def ignoref(directory, contents):
return (f for f in contents if os.abspath(os.path.join(directory, f)) == path)
return ignoref
shutil.copytree('Path', 'target', ignore=ignorePath('/Full/Path/To/aDir/Common'))
Run Code Online (Sandbox Code Playgroud)
来自文档:
如果给出了ignore,则它必须是一个可调用的,它将接收copytree()访问的目录作为其参数,以及os.listdir()返回的内容列表.由于copytree()是递归调用的,因此对于每个复制的目录,将调用ignore callable一次.callable必须返回相对于当前目录的一系列目录和文件名(即第二个参数中的项的子集); 这些名称将在复制过程中被忽略.ignore_patterns()可用于创建一个基于glob样式模式忽略名称的可调用对象.