25 November 2015

Just know a new module in Python standard library called glob. This module helps you get files in your desired pattern. * matches any characters, ?matches single character, [] matches a character in square brackets range.

For example, if you have files

12abc.pdf
ut.bmp
051.txt
uc.pdf

Here is some examples of glob.glob(pathname):

import glob
glob.glob("*.*")

['051.txt', '12abc.pdf', 'uc.pdf', 'ut.bmp']

glob.glob("[0-9]*.*")

['051.txt', '12abc.pdf']

glob.glob("[0-9]*.pdf")

['12abc.pdf']

glob.glob("[0-9].pdf")

[]

glob.glob("?.*")
glob.glob("?.pdf")
glob.glob("??.pdf")

[] [] ['uc.pdf']

There is another function glob.iglob(pathname) which return yields the same values as glob() as an iterator.

The official documents can be find here