May 2001
Intermediate to advanced
304 pages
6h 12m
English
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.jpgIn 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.
Read now
Unlock full access