find_files: 根据子字符串匹配查找文件

一个函数,用于在给定目录中根据子字符串匹配查找文件,并返回找到的文件名列表。

from mlxtend.file_io import find_files

概述

此函数基于子字符串搜索查找文件。如果我们想在目录树中查找特定文件并返回其绝对路径以便在 Python 中进一步处理,此功能特别有用。

参考资料

  • -

给定以下目录和文件结构

dir_1/
    file_1.log
    file_2.log
    file_3.log
dir_2/
    file_1.csv
    file_2.csv
    file_3.csv
dir_3/
    file_1.txt
    file_2.txt
    file_3.txt

我们可以使用 find_files 返回包含子字符串 _2 的所有文件的路径,如下所示

from mlxtend.file_io import find_files

find_files(substring='_2', path='./data_find_filegroups/', recursive=True)
['./data_find_filegroups/dir_1/file_2.log',
 './data_find_filegroups/dir_2/file_2.csv',
 './data_find_filegroups/dir_3/file_2.txt']

API

find_files(substring, path, recursive=False, check_ext=None, ignore_invisible=True, ignore_substring=None)

在目录中根据子字符串匹配查找文件。

参数

  • substring : str

    要匹配的文件子字符串。

  • path : str

    要查找的路径。

  • recursive : bool

    如果为 True,则递归搜索子目录。

  • check_ext : str

    如果为字符串(例如,'.txt'),则仅返回匹配指定文件扩展名的文件。

  • ignore_invisible : bool

    如果为 True,则忽略不可见文件(即,以点开头的文件)。

  • ignore_substring : str

    忽略包含指定子字符串的文件。

返回

  • results : list

    匹配文件的列表。

示例

有关使用示例,请参阅 https://mlxtend.cn/mlxtend/user_guide/file_io/find_files/