Column address: a Python module per week
Meanwhile, welcome to follow my wechat official account AlwaysBeta, more exciting content waiting for you.
The fnmatch module is mainly used for file name comparison, using the Glob style pattern used by Unix shells.
Simple matching
Fnmatch () compares individual file names to patterns and returns a Boolean value to see if they match. If the operating system uses a case-sensitive file system, the file system is case-sensitive.
import fnmatch
import os
pattern = 'fnmatch_*.py'
print('Pattern :', pattern)
print()
files = os.listdir('. ')
for name in sorted(files):
print('Filename: {:<25} {}'.format(name, fnmatch.fnmatch(name, pattern)))
# output
# Pattern : fnmatch_*.py
#
# Filename: fnmatch_filter.py True
# Filename: fnmatch_fnmatch.py True
# Filename: fnmatch_fnmatchcase.py True
# Filename: fnmatch_translate.py True
# Filename: index.rst False
Copy the code
In this example, the pattern matches all files that start with ‘fnmatch_’ and end with ‘.py’.
To force case-sensitive comparisons, regardless of file system and operating system Settings, use fnMatchCase ().
import fnmatch
import os
pattern = 'FNMATCH_*.PY'
print('Pattern :', pattern)
print()
files = os.listdir('. ')
for name in sorted(files):
print('Filename: {:<25} {}'.format(name, fnmatch.fnmatchcase(name, pattern)))
# output
# Pattern : FNMATCH_*.PY
#
# Filename: fnmatch_filter.py False
# Filename: fnmatch_fnmatch.py False
# Filename: fnmatch_fnmatchcase.py False
# Filename: fnmatch_translate.py False
# Filename: index.rst False
Copy the code
Because the OS X system used to test this program uses a case-sensitive file system, no files match the modified schema.
filter
To test the filename sequence, use filter(), which returns a list of names that match the pattern argument.
import fnmatch
import os
import pprint
pattern = 'fnmatch_*.py'
print('Pattern :', pattern)
files = list(sorted(os.listdir('. ')))
print('\nFiles :')
pprint.pprint(files)
print('\nMatches :')
pprint.pprint(fnmatch.filter(files, pattern))
# output
# Pattern : fnmatch_*.py
#
# Files :
# ['fnmatch_filter.py',
# 'fnmatch_fnmatch.py',
# 'fnmatch_fnmatchcase.py',
# 'fnmatch_translate.py',
# 'index.rst']
#
# Matches :
# ['fnmatch_filter.py',
# 'fnmatch_fnmatch.py',
# 'fnmatch_fnmatchcase.py',
# 'fnmatch_translate.py']
Copy the code
In this example, filter() returns a list of the names of the sample source files associated with this section.
Translation mode
Internally, FnMatch converts glob patterns into regular expressions and uses the RE module to compare names and patterns. The translate() function is a public API for converting glob patterns into regular expressions.
import fnmatch
pattern = 'fnmatch_*.py'
print('Pattern :', pattern) # Pattern : fnmatch_*.py
print('Regex :', fnmatch.translate(pattern)) # Regex : (? s:fnmatch_.*\.py)\Z
Copy the code
Original link:
Pymotw.com/3/fnmatch/i…