天天看点

python中glob_python中的glob模块

简介

glob模块可以查找符合特定规则的文件路径名。跟使用windows下的文件搜索差不多。它有三个匹配符:”*”, “?”, “[]”。

*:匹配0个或多个字符;

?:匹配单个字符;

[]:匹配指定范围内的字符,如:[a-z]匹配所有字母

方法介绍

.glob(pathname, *, recursive=False)

"""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.

If recursive is true, the pattern '**' will match any files and

zero or more directories and subdirectories.

"""

# recursive默认为False,表示只返回该路径下的目录及文件列表;如果为True,则路径后应该跟**,可递归返回该路径下的所有目录及目录下的文件,否则效果跟False一样

glob.glob(r"C:\Users\Desktop\FinanicalBook\.*") # 返回所有的隐藏目录及文件列表

glob.glob(r"C:\Users\Desktop\FinanicalBook\*") # 返回FinanicalBook目录下的所有目录及文件列表

glob.glob(r"C:\Users\Desktop\FinanicalBook\a*") # 返回以a开头的目录及文件列表

glob.glob(r"C:\Users\Desktop\FinanicalBook\*q") # 返回以q结尾的目录及文件列表

glob.glob(r"C:\Users\Desktop\FinanicalBook\[a-c]*") # 返回以a-c开头的目录及文件列表

glob.glob(r"C:\Users\Desktop\FinanicalBook\**", recursive=True) # 递归匹配任何文件以及零个或多个目录和子目录

.iglob(pathname, *, recursive=False)

用法跟glob()一样,只不过该函数的返回值是一个generator(生成器)

.escape(pathname)

"""

Escape all special characters.

Escaping is done by wrapping any of "*?[" between square brackets

"""

# 转义所有特殊字符

# 转义是通过在方括号之间包装“*?[”来完成的

# 例:

res = glob.escape(r"C:\Users\Desktop\FinanicalBook\*..\?\[A-Z^$|\res")

# C:\Users\Desktop\FinanicalBook\[*]..\[?]\[[]A-Z^$|\res