How To Use Python Fnmatch Module To Handle File Name Matching

Python fnmatch module can support UNIX shell style filename matching. And the python fnmatch matches support the following wildcards and functions.

1. Python fnmatch Module Supported Wildcards & Functions.

  1. *: it can match any character.
  2. ?: it can match any single character.
  3. >[character sequence]: it can match any character in the character sequence in brackets. The character sequence also supports middle line representation. For example, [a-c] can represent any of the characters in a, b, and c.
  4. >[! character sequence]: it can match any character not in the bracket character sequence.
  5. fnmatch.fnmatch(filename, pattern) , this function determines whether the specified file name matches the specified pattern.
  6. fnmatch.fnmatchcase(file name, pattern): this function is similar to the previous function except that it is case sensitive.
  7. fnmatch.filter(names, pattern): this function filters the names list and returns a subset of file names that match the patterns.
  8. fnmatch.translate(pattern): this function is used to convert a UNIX shell style pattern to a regular expression pattern.

2. Python fnmatch Module Examples.

The following python code example demonstrates the above function usage.

fnmatch.fnmatch(filename, pattern): This example will filter out all the python files under the current directory.

from pathlib import *
import fnmatch
import os.path

# Traverse all the files and subdirectories under the current directory
curr_dir = Path('.')
for f in curr_dir.iterdir():
    
    # If the file name end with .py.
    if fnmatch.fnmatch(f, '*.py'):
        
        # Get the file absolute path.
        f_path = os.path.abspath('.') + '/'+f.name
        
        # Print the file path.
        print(f_path)

========================================================
Output
/Users/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/file/FileOperateExample.py
/Users/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/file/CheckFileExistExample.py
/Users/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/file/OsWalk.py

fnmatch.filter(names, pattern)

import fnmatch

if __name__ == '__main__':         
     
    # Define a list contains 4 python file, fnmatch module do not care whether the files exists or not.        
    file_names = ['a.py','b.py','c.py','d.py']
    
    # Define a pattern string.
    name_pattern = '[bc].py'
    
    # Filter the python file name list with the file name pattern.
    sub_file_names = fnmatch.filter(file_names, name_pattern)
    
    # Print out the filter result.
    print(sub_file_names)

======================================================
Output 

['b.py', 'c.py']

fnmatch.translate(pattern)

import fnmatch

unix_pattern_str = '?.py'
reg_pattern_str = fnmatch.translate(unix_pattern_str)
print(reg_pattern_str)
    
unix_pattern_str = '[a-z].py'
reg_pattern_str = fnmatch.translate(unix_pattern_str)
print(reg_pattern_str)
    
unix_pattern_str = '[xyz].py'
reg_pattern_str = fnmatch.translate(unix_pattern_str)
print(reg_pattern_str)
=======================================================
Output

(?s:.\.py)\Z
(?s:[a-z]\.py)\Z
(?s:[xyz]\.py)\Z
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x