当前位置: 首页 > 面试题库 >

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

叶桐
2023-03-14
问题内容

我正在寻找一种包含/排除文件模式并从os.walk()呼叫中排除目录的方法。

这是我现在正在做的事情:

import fnmatch
import os

includes = ['*.doc', '*.odt']
excludes = ['/home/paulo-freitas/Documents']

def _filter(paths):
    for path in paths:
        if os.path.isdir(path) and not path in excludes:
            yield path

        for pattern in (includes + excludes):
            if not os.path.isdir(path) and fnmatch.fnmatch(path, pattern):
                yield path

for root, dirs, files in os.walk('/home/paulo-freitas'):
    dirs[:] = _filter(map(lambda d: os.path.join(root, d), dirs))
    files[:] = _filter(map(lambda f: os.path.join(root, f), files))

    for filename in files:
        filename = os.path.join(root, filename)

        print(filename)

有一个更好的方法吗?怎么样?


问题答案:

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

import fnmatch
import os
import os.path
import re

includes = ['*.doc', '*.odt'] # for files only
excludes = ['/home/paulo-freitas/Documents'] # for dirs and files

# transform glob patterns to regular expressions
includes = 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


 类似资料:
  • 本文向大家介绍python 获取文件下所有文件或目录os.walk()的实例,包括了python 获取文件下所有文件或目录os.walk()的实例的使用技巧和注意事项,需要的朋友参考一下 在python3.6版本中去掉了os.path.walk()函数 os.walk() 函数声明:walk(top,topdown=True,oneerror=None) 1、参数top表示需要遍历的目录树的路径

  • 我有一个文件夹,其中有对应于10个不同类的子文件夹,这些子文件夹的名称是我的标签。我想出了以下代码来将图像读入Numpy数组并保存标签。 我得到的错误是 os.chdir(root)FileNotFoundError:[Errno 2]没有这样的文件或目录:“U” 当I时,它会给出正确的子文件夹路径。如何处理此错误? 编辑:通过删除根目录中的根目录的

  • 本章主要介绍文件和目录操作,包含以下部分: 读写文本文件 读写二进制文件 os 模块

  • 文件和目录操作接口 函数 int  open (const char *file, int flags,...)   打开文件   int  close (int fd)   关闭文件   int  read (int fd, void *buf, size_t len)   读取数据   int  write (int fd, const void *buf, size_t len)   写入数

  • 本文向大家介绍Python使用os.listdir()和os.walk()获取文件路径与文件下所有目录的方法,包括了Python使用os.listdir()和os.walk()获取文件路径与文件下所有目录的方法的使用技巧和注意事项,需要的朋友参考一下 在python3.6版本中去掉了os.path.walk()函数 os.walk() 函数声明:walk(top,topdown=True,onee

  • 问题内容: 如何限制仅返回提供的目录中的文件? 问题答案: 使用功能。 它的工作方式与相似,但是您可以向其传递一个参数,该参数指示递归的深度。