The glob Module

The glob module generates lists of files matching given patterns, just like the Unix shell.

File patterns are similar to regular expressions, but simpler. An asterisk (*) matches zero or more characters, and a question mark (?) matches exactly one character. You can also use brackets to indicate character ranges, such as [0-9] for a single digit. All other characters match themselves.

glob(pattern) returns a list of all files matching a given pattern. The glob module is demonstrated in Example 2-26.

Example 2-26. Using the glob Module

File: glob-example-1.py import glob for file in glob.glob("samples/*.jpg"): print file samples/sample.jpg

Note that glob returns full pathnames, unlike the os.listdir function. glob uses the fnmatch module to do the actual pattern matching.

Категории