Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python fnmatch module: for filename matching

The fnmatch module in Python provides functions to compare filenames against shell-style wildcards, which can be used to filter and match filenames based on patterns. In this tutorial, we will learn how to use the fnmatch module to match and filter filenames in Python.

  • Import the fnmatch module:

To use the fnmatch module, you need to import it first.

import fnmatch
  • Matching filenames using fnmatch.fnmatch():

The fnmatch.fnmatch() function is used to match a filename against a shell-style wildcard pattern. It takes two arguments: the filename and the pattern. The function returns True if the filename matches the pattern, and False otherwise.

import fnmatch

filename = "example.txt"
pattern = "*.txt"

if fnmatch.fnmatch(filename, pattern):
    print(f"{filename} matches the pattern {pattern}")
else:
    print(f"{filename} does not match the pattern {pattern}")

In this example, we check if the filename example.txt matches the pattern *.txt. The * wildcard matches any sequence of characters.

  • Filtering filenames using fnmatch.filter():

The fnmatch.filter() function is used to filter a list of filenames based on a shell-style wildcard pattern. It takes two arguments: a list of filenames and the pattern. The function returns a list of filenames that match the pattern.

import fnmatch

filenames = ["file1.txt", "file2.doc", "file3.txt", "file4.pdf"]
pattern = "*.txt"

matched_filenames = fnmatch.filter(filenames, pattern)
print(matched_filenames)  # Output: ['file1.txt', 'file3.txt']

In this example, we filter a list of filenames to keep only those that match the pattern *.txt.

  • Using shell-style wildcards:

Here are some common shell-style wildcards that can be used with fnmatch:

  • *: Matches any sequence of characters.
  • ?: Matches any single character.
  • [seq]: Matches any character in seq. For example, [abc] matches any of the characters 'a', 'b', or 'c'.
  • [!seq]: Matches any character not in seq. For example, [!abc] matches any character except 'a', 'b', and 'c'.

Example:

import fnmatch

filenames = ["file1.txt", "file2.doc", "file3.txt", "file4.pdf", "file5.tex"]
pattern = "file?.[dp]*"

matched_filenames = fnmatch.filter(filenames, pattern)
print(matched_filenames)  # Output: ['file2.doc', 'file4.pdf']

In this example, we filter a list of filenames to keep only those that match the pattern file?.[dp]*. The ? wildcard matches any single character, and the [dp] sequence matches either 'd' or 'p'.

In summary, the fnmatch module in Python provides functions for matching and filtering filenames based on shell-style wildcard patterns. The fnmatch.fnmatch() function can be used to match a single filename against a pattern, while the fnmatch.filter() function can be used to filter a list of filenames based on a pattern. The module supports various shell-style wildcards such as *, ?, [seq], and [!seq].

  1. How to use fnmatch for filename matching in Python:

    • Description: The fnmatch module is used for simple filename matching based on Unix shell-style wildcards.
    • Code:
      import fnmatch
      
      file_name = "example.txt"
      pattern = "*.txt"
      
      if fnmatch.fnmatch(file_name, pattern):
          print("Match found!")
      
  2. Wildcard pattern matching with fnmatch in Python:

    • Description: Use wildcards (* for any number of characters, ? for a single character) in patterns for flexible matching.
    • Code:
      import fnmatch
      
      file_name = "example.txt"
      pattern = "ex*ple.txt"
      
      if fnmatch.fnmatch(file_name, pattern):
          print("Match found!")
      
  3. Case-insensitive filename matching with fnmatch:

    • Description: Use the fnmatchcase function for case-insensitive filename matching.
    • Code:
      import fnmatch
      
      file_name = "Example.txt"
      pattern = "example.txt"
      
      if fnmatch.fnmatchcase(file_name, pattern):
          print("Match found!")
      
  4. Filtering files using fnmatch in Python:

    • Description: Filter a list of filenames based on a specific pattern using fnmatch.filter.
    • Code:
      import fnmatch
      
      file_names = ["file1.txt", "file2.txt", "image.jpg", "document.pdf"]
      pattern = "*.txt"
      
      filtered_files = fnmatch.filter(file_names, pattern)
      print(filtered_files)
      
  5. Matching multiple patterns with fnmatch in Python:

    • Description: Match filenames against multiple patterns using a loop or list comprehension.
    • Code:
      import fnmatch
      
      file_name = "example.txt"
      patterns = ["ex*.txt", "*.pdf"]
      
      if any(fnmatch.fnmatch(file_name, pattern) for pattern in patterns):
          print("Match found!")
      
  6. Using fnmatch to find files in a directory in Python:

    • Description: Use os.listdir with fnmatch.filter to find files in a directory based on a pattern.
    • Code:
      import os
      import fnmatch
      
      directory_path = "/path/to/files"
      pattern = "*.txt"
      
      files_in_directory = os.listdir(directory_path)
      filtered_files = fnmatch.filter(files_in_directory, pattern)
      print(filtered_files)
      
  7. Customizing filename matching behavior with fnmatch:

    • Description: Customize matching behavior using the fnmatch.translate function for more advanced patterns.
    • Code:
      import fnmatch
      
      file_name = "example.txt"
      pattern = "ex*[0-9].txt"
      
      compiled_pattern = fnmatch.translate(pattern)
      if fnmatch.fnmatch(file_name, compiled_pattern):
          print("Match found!")
      
  8. Comparing fnmatch with regular expressions in Python:

    • Description: While fnmatch is simpler for basic matching, regular expressions provide more advanced pattern matching capabilities.
    • Code:
      import re
      
      file_name = "example.txt"
      pattern = "ex.*\.txt"
      
      if re.match(pattern, file_name):
          print("Match found using regular expression!")
      
  9. Pattern matching and exclusion with fnmatch in Python:

    • Description: Use fnmatch.filter with additional conditions for both pattern matching and exclusion.
    • Code:
      import fnmatch
      
      file_names = ["file1.txt", "file2.txt", "image.jpg", "document.pdf"]
      include_pattern = "*.txt"
      exclude_pattern = "file*.txt"
      
      filtered_files = [file for file in file_names if fnmatch.fnmatch(file, include_pattern) and not fnmatch.fnmatch(file, exclude_pattern)]
      print(filtered_files)
      
  10. Recursive file searching with fnmatch in Python:

    • Description: Recursively search for files in subdirectories using os.walk and fnmatch.filter.
    • Code:
      import os
      import fnmatch
      
      root_directory = "/path/to/files"
      pattern = "*.txt"
      
      for root, dirs, files in os.walk(root_directory):
          filtered_files = fnmatch.filter(files, pattern)
          for file in filtered_files:
              print(os.path.join(root, file))
      
  11. Handling special characters in filenames with fnmatch:

    • Description: Escape special characters in patterns using re.escape to ensure accurate matching.
    • Code:
      import fnmatch
      import re
      
      file_name = "file[1].txt"
      pattern = "file[1].txt"
      
      escaped_pattern = re.escape(pattern)
      if fnmatch.fnmatch(file_name, escaped_pattern):
          print("Match found!")