python glob fnmatch 用于文件查找操作

参考:

http://python.jobbole.com/81552/:Python模块学习:glob文件路径查找

http://blog.csdn.net/suiyunonghen/article/details/4517103:python中的一个好用的文件名操作模块glob

https://docs.python.org/2/library/glob.html:10.7. glob - Unix style pathname pattern expansion

https://docs.python.org/2/library/fnmatch.html#module-fnmatch:10.8. fnmatch - Unix filename pattern matching


#################################################################3


测试集文件分布情况:

python glob fnmatch 用于文件查找操作_第1张图片


3##############################################################3


本人glob源码位置:/usr/lib/python2.7/glob.py

python glob fnmatch 用于文件查找操作_第2张图片


函数名:glob

参数名:pathname - 路径名(可以使用相对路径或绝对路径)

功能:返回一个列表,存储所有匹配你参数名的文件路径(当你使用相对路径时,文件路径为相对路径;当你使用绝对路径时,文件路径为绝对路径)

note:查找的范围仅在路径名所在目录


路径名必须使用通配符,不过只有三种(*/?/[])。*代表所有文件,?代表一个字符,[]表示想要匹配的多个字符(比如,[0-9]表示匹配数字0-9)


查找当前目录下所有文件和目录:

python glob fnmatch 用于文件查找操作_第3张图片


note:由上图可知,仅提供路径并不会得到任何结果


查找当前目录下的txt文件:



已知测试集共有三层

查找第二层的所有txt文件:



函数iglob(pathname)功能和glob类似,只不过iglob返回的是迭代器。查看源码可知,两个函数其实一模一样

def glob(pathname):
    """Return a list of paths matching a pathname pattern.

    The pattern may contain simple shell-style wildcards a la
    fnmatch. However, unlike fnmatch, filenames starting with a
    dot are special cases that are not matched by '*' and '?'
    patterns.

    """
    return list(iglob(pathname))

###########################################################################33


本人fnmatch源码位置:/usr/lib/python2.7/fnmatch.py

共有四个函数:



函数filter:

python glob fnmatch 用于文件查找操作_第4张图片

返回列表names中符合模式pat的子集

python glob fnmatch 用于文件查找操作_第5张图片


函数fnmatch

python glob fnmatch 用于文件查找操作_第6张图片

测试name是否符合pat的模式

pat格式符合Unix文本类型:

*-表示所有

?-表示一个单一字符

[seq]-表示符合[]内的序列的字符

[!seq]-表示不符合[]内的序列的字符


查看源码知,该函数功能和fnmatcncase一样:

def fnmatch(name, pat):
    """Test whether FILENAME matches PATTERN.

    Patterns are Unix shell style:

    *       matches everything
    ?       matches any single character
    [seq]   matches any character in seq
    [!seq]  matches any char not in seq

    An initial period in FILENAME is not special.
    Both FILENAME and PATTERN are first case-normalized
    if the operating system requires it.
    If you don't want this, use fnmatchcase(FILENAME, PATTERN).
    """

    import os
    name = os.path.normcase(name)
    pat = os.path.normcase(pat)
    return fnmatchcase(name, pat)

函数fnmatchcase

python glob fnmatch 用于文件查找操作_第7张图片

没有规范化参数,仅仅判断文件名是否匹配模式符,包括大小写

python glob fnmatch 用于文件查找操作_第8张图片


note:参数均为单个字符串


你可能感兴趣的:(python)