I l@ve RuBoard Previous Section Next Section

2.16 The fnmatch Module

The fnmatch module matches filenames against a pattern, as Example 2-27 shows.

The pattern syntax is the same as that used in Unix shells. 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.

Example 2-27. Using the fnmatch Module to Match Files
File: fnmatch-example-1.py

import fnmatch
import os

for file in os.listdir("samples"):
    if fnmatch.fnmatch(file, "*.jpg"):
        print file

sample.jpg

In Example 2-28, the translate function converts a file pattern to a regular expression.

Example 2-28. Using the fnmatch Module to Convert a Pattern to a Regular Expression
File: fnmatch-example-2.py

import fnmatch
import os, re

pattern = fnmatch.translate("*.jpg")

for file in os.listdir("samples"):
    if re.match(pattern, file):
        print file

print "(pattern was %s)" % pattern

sample.jpg
(pattern was .*\.jpg$)

The fnmatch module is used by the glob and find modules.

    I l@ve RuBoard Previous Section Next Section