Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Unix filename pattern matching in Python
Unix filename pattern matching in Python is accomplished using the fnmatch module. This module provides shell-style pattern matching capabilities to compare filenames against patterns and returns True or False based on matches.
Importing the fnmatch Module
First, import the fnmatch module from Python's standard library ?
import fnmatch
Unix Wildcard Patterns
The fnmatch module supports standard Unix wildcards ?
-
*− Matches any number of characters (including none) -
?− Matches exactly one character -
[seq]− Matches any character in the sequence -
[!seq]− Matches any character not in the sequence
To search for literal asterisk or question mark characters, use [*] or [?].
The fnmatch() Method
The fnmatch() method compares a filename against a pattern. It takes two arguments: the filename and the pattern ?
import fnmatch
# Test various patterns
patterns = [
('hello.txt', 'h*.txt'),
('test123.py', 'test???.py'),
('data.csv', '*.csv'),
('file.TXT', '*.txt') # Case sensitive
]
for filename, pattern in patterns:
result = fnmatch.fnmatch(filename, pattern)
print(f'File: {filename:12} Pattern: {pattern:10} Match: {result}')
File: hello.txt Pattern: h*.txt Match: True File: test123.py Pattern: test???.py Match: True File: data.csv Pattern: *.csv Match: True File: file.TXT Pattern: *.txt Match: False
The filter() Method
The filter() method returns a list of filenames that match the pattern. It takes a list of names and a pattern as parameters ?
import fnmatch
files = ['test_file1.txt', 'test_file2.png', 'another_file.txt',
'test_file3.txt', 'abc.txt', 'TEST_FILE4.txt']
pattern = 'test_f*'
matched_files = fnmatch.filter(files, pattern)
print('All files:', files)
print('\nMatched files:', matched_files)
All files: ['test_file1.txt', 'test_file2.png', 'another_file.txt', 'test_file3.txt', 'abc.txt', 'TEST_FILE4.txt'] Matched files: ['test_file1.txt', 'test_file2.png', 'test_file3.txt']
The translate() Method
The translate() method converts shell-style patterns to regular expressions. This is useful when you need regex pattern objects ?
import fnmatch
import re
pattern = 'test_f*.txt'
regex_pattern = fnmatch.translate(pattern)
regex_object = re.compile(regex_pattern)
print('Original pattern:', pattern)
print('Regular expression:', regex_pattern)
# Test the regex
test_file = 'test_file_abcd123.txt'
match = regex_object.match(test_file)
print(f'Match result: {match}')
Original pattern: test_f*.txt Regular expression: (?s:test_f.*\.txt)\Z Match result: <re.Match object; span=(0, 21), match='test_file_abcd123.txt'>
Practical Example
Here's a complete example showing how to find specific file types in a directory ?
import fnmatch
import os
def find_files(directory, pattern):
"""Find files matching pattern in directory"""
try:
all_files = os.listdir(directory)
matching_files = fnmatch.filter(all_files, pattern)
return matching_files
except FileNotFoundError:
return []
# Example usage
patterns = ['*.txt', '*.py', 'test_*']
directory = './files'
for pattern in patterns:
matches = find_files(directory, pattern)
print(f'Files matching "{pattern}": {matches}')
Conclusion
The fnmatch module provides powerful Unix-style pattern matching for filenames. Use fnmatch() for single file checks, filter() for filtering lists, and translate() when you need regex objects for complex matching operations.
