过滤os.walk()目录和文件

过滤os.walk()目录和文件,第1张

过滤os.walk()目录和文件

此解决方案用于

fnmatch.translate
将glob模式转换为正则表达式(假定include仅用于文件):

import fnmatchimport osimport os.pathimport reincludes = ['*.doc', '*.odt'] # for files onlyexcludes = ['/home/paulo-freitas/documents'] # for dirs and files# transform glob patterns to regular expressionsincludes = r'|'.join([fnmatch.translate(x) for x in includes])excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'for root, dirs, files in os.walk('/home/paulo-freitas'):    # exclude dirs    dirs[:] = [os.path.join(root, d) for d in dirs]    dirs[:] = [d for d in dirs if not re.match(excludes, d)]    # exclude/include files    files = [os.path.join(root, f) for f in files]    files = [f for f in files if not re.match(excludes, f)]    files = [f for f in files if re.match(includes, f)]    for fname in files:        print fname


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5623413.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存