The fnmatch
module in Python provides support for Unix shell-style wildcards to match filenames. It offers simple functions to compare filenames against a pattern, making it useful for filtering file names based on patterns.
Table of Contents
- Introduction
- Key Functions
fnmatch
fnmatchcase
filter
translate
- Wildcards
*
?
[]
- Examples
- Basic Usage
- Case-Sensitive Matching
- Filtering File Lists
- Real-World Use Case
- Conclusion
- References
Introduction
The fnmatch
module is used to compare filenames against a pattern. It supports Unix shell-style wildcards, which makes it easier to filter and match filenames in a directory or list.
Key Functions
fnmatch
Checks if a filename matches a pattern. The comparison is case-insensitive on Windows and case-sensitive on Unix.
import fnmatch
print(fnmatch.fnmatch('example.txt', '*.txt')) # True
print(fnmatch.fnmatch('example.TXT', '*.txt')) # True on Windows, False on Unix
fnmatchcase
Performs a case-sensitive comparison, regardless of the operating system.
import fnmatch
print(fnmatch.fnmatchcase('example.txt', '*.TXT')) # False
print(fnmatch.fnmatchcase('example.TXT', '*.TXT')) # True
filter
Filters a list of filenames to include only those that match a pattern.
import fnmatch
filenames = ['file1.txt', 'file2.txt', 'file3.py', 'script.py']
print(fnmatch.filter(filenames, '*.py')) # ['file3.py', 'script.py']
translate
Returns a string containing the regex pattern equivalent to the wildcard pattern.
import fnmatch
pattern = fnmatch.translate('*.txt')
print(pattern) # '.*\\.txt\\Z(?ms)'
Wildcards
*
Matches zero or more characters.
import fnmatch
print(fnmatch.fnmatch('file.txt', '*.txt')) # True
print(fnmatch.fnmatch('file.txt', '*.*')) # True
?
Matches exactly one character.
import fnmatch
print(fnmatch.fnmatch('file.txt', 'f?le.txt')) # True
print(fnmatch.fnmatch('file.txt', 'f?le.tx?')) # True
[]
Matches any one of the enclosed characters.
import fnmatch
print(fnmatch.fnmatch('file.txt', '[fF]ile.txt')) # True
print(fnmatch.fnmatch('File.txt', '[fF]ile.txt')) # True
print(fnmatch.fnmatch('file.txt', '[a-z]ile.txt')) # True
Examples
Basic Usage
import fnmatch
filename = 'data.csv'
pattern = '*.csv'
if fnmatch.fnmatch(filename, pattern):
print(f"{filename} matches the pattern {pattern}")
Case-Sensitive Matching
import fnmatch
filename = 'Data.CSV'
pattern = '*.CSV'
if fnmatch.fnmatchcase(filename, pattern):
print(f"{filename} matches the pattern {pattern} (case-sensitive)")
else:
print(f"{filename} does not match the pattern {pattern} (case-sensitive)")
Filtering File Lists
import fnmatch
filenames = ['data1.csv', 'data2.txt', 'data3.csv', 'report.doc']
csv_files = fnmatch.filter(filenames, '*.csv')
print(f"CSV files: {csv_files}") # ['data1.csv', 'data3.csv']
Real-World Use Case
Finding Log Files
import fnmatch
import os
log_dir = '/path/to/logs'
pattern = '*.log'
log_files = [f for f in os.listdir(log_dir) if fnmatch.fnmatch(f, pattern)]
for log_file in log_files:
print(f"Processing log file: {log_file}")
# Perform processing on the log file
Conclusion
The fnmatch
module in Python provides a simple and effective way to match filenames using Unix shell-style wildcards. It is useful for filtering and finding files based on patterns, making it a handy tool for file manipulation tasks.
Comments
Post a Comment
Leave Comment