glob是Python自己带的一个文件操作相关模块,用它可以查找符合自己目的的文件,就类似于Windows下的文件搜索,支持通配符操作,*,?,[]这三个通配符,*代表0个或多个字符,?代表一个字符,[]匹配指定范围内的字符,如[0-9]匹配数字。
它的主要方法就是glob,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),其返回的文件名只包括当前目录里的文件名,不包括子文件夹里的文件。
python手机中的介绍:
Theglobmodule finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. No tilde expansion is done, but*,?, and character ranges expressed with[]will be correctly matched. This is done by using theos.listdir()andfnmatch.fnmatch()functions in concert, and not by actually invoking a subshell. (For tilde and shell variable expansion, useos.path.expanduser()andos.path.expandvars().)
glob.glob(pathname) #返回列表
Return a possibly-empty list of path names that matchpathname, which must be a string containing a path specification.pathnamecan be either absolute (like/usr/src/Python-1.5/Makefile) or relative (like../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).
glob.iglob(pathname) #返回迭代器
Return aniteratorwhich yields the same values asglob()without actually storing them all simultaneously.
New in version 2.5.
For example, consider a directory containing only the following files:1.gif,2.txt, andcard.gif.glob()will produce the following results. Notice how any leading components of the path are preserved.
上代码:
结果: