glob.py

来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 57 行

PY
57
字号
"""Filename globbing utility."""import osimport fnmatchimport re__all__ = ["glob"]def glob(pathname):    """Return a list of paths matching a pathname pattern.    The pattern may contain simple shell-style wildcards a la fnmatch.    """    if not has_magic(pathname):        if os.path.exists(pathname):            return [pathname]        else:            return []    dirname, basename = os.path.split(pathname)    if not dirname:        return glob1(os.curdir, basename)    elif has_magic(dirname):        list = glob(dirname)    else:        list = [dirname]    if not has_magic(basename):        result = []        for dirname in list:            if basename or os.path.isdir(dirname):                name = os.path.join(dirname, basename)                if os.path.exists(name):                    result.append(name)    else:        result = []        for dirname in list:            sublist = glob1(dirname, basename)            for name in sublist:                result.append(os.path.join(dirname, name))    return resultdef glob1(dirname, pattern):    if not dirname: dirname = os.curdir    try:        names = os.listdir(dirname)    except os.error:        return []    if pattern[0]!='.':        names=filter(lambda x: x[0]!='.',names)    return fnmatch.filter(names,pattern)magic_check = re.compile('[*?[]')def has_magic(s):    return magic_check.search(s) is not None

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?