关于ZAKER 融媒体解决方案 合作 加入

使用 shutil.copytree 时筛选目录?

CocoaChina 10-23

有没有一种方法可以使用目录的绝对路径来过滤目录?

shutil.copytree ( directory, target_dir, ignore = shutil.ignore_patterns ( "/Full/Path/To/aDir/Common" ) )

尝试过滤位于 " aDir" 下的 " 公用 " 目录时 , 这似乎不起作用 . 如果我这样做:

shutil.copytree ( directory, target_dir, ignore = shutil.ignore_patterns ( "Common" ) )

它可以工作 , 但是每个称为 Common 的目录都将在该 " 树 " 中被过滤 , 这不是我想要的 .

有什么建议么 ?

谢谢 .

最佳答案

您可以创建自己的忽略函数:

shutil.copytree ( '/Full/Path', 'target', ignore=lambda directory, contents: [ 'Common' ] if directory == '/Full/Path/To/aDir' else [ ] )

或者 , 如果您希望能够使用相对路径调用 copytree:

import os.pathdef ignorePath ( path ) : def ignoref ( directory, contents ) : return ( f for f in contents if os.abspath ( os.path.join ( directory, f ) ) == path ) return ignorefshutil.copytree ( 'Path', 'target', ignore=ignorePath ( '/Full/Path/To/aDir/Common' ) )

从文档:

If ignore is given, it must be a callable that will receive as its

arguments the directory being visited by copytree ( ) , and a list of its

contents, as returned by os.listdir ( ) . Since copytree ( ) is called

recursively, the ignore callable will be called once for each

directory that is copied. The callable must return a sequence of

directory and file names relative to the current directory ( i.e. a

subset of the items in its second argument ) ; these names will then be

ignored in the copy process. ignore_patterns ( ) can be used to create

such a callable that ignores names based on glob-style patterns.

以上内容由"CocoaChina"上传发布 查看原文
相关标签 目录

觉得文章不错,微信扫描分享好友

扫码分享