Python偶遇glob

3,699次阅读
没有评论

共计 1789 个字符,预计需要花费 5 分钟才能阅读完成。

Python偶遇glob

今天在看一个代码的时候发现glob,源代码是需要将子目录里面所有带指定后缀名的文件检索出来,我们并不关心文件的名字,只关心文件后缀名。代码中给出了glob函数的操作,通过给出正则表达式匹配所有的文件并返回列表,找到则不为空。有了这个就不需要自己去便利每一个子目录了。。。。Python的包真的是多,知道能省很多时间,不知道又要自己造轮子了。。。。。

glob 路径模式匹配


The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *?, and character ranges expressed with [] will be correctly matched. This is done by using the os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell. Note that unlike fnmatch.fnmatch(),glob treats filenames beginning with a dot (.) as special cases. (For tilde and shell variable expansion, use os.path.expanduser() and os.path.expandvars().)

For a literal match, wrap the meta-characters in brackets. For example, '[?]' matches the character '?'.

glob.glob(pathname)
Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can 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 an iterator which yields the same values as glob() without actually storing them all simultaneously.

New in version 2.5.

For example, consider a directory containing only the following files: 1.gif2.txt, and card.gifglob() will produce the following results. Notice how any leading components of the path are preserved.

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']

If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

在这里要注意一下开头是 . 的文件,这个是不能被正则式 * 识别出来,这一点需要注意一下

>>> import glob
>>> glob.glob('*.gif')
['card.gif']
>>> glob.glob('.c*')
['.card.gif']
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2018-03-26发表,共计1789字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码