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)
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.
fnmatch
module:To use the fnmatch
module, you need to import it first.
import fnmatch
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.
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
.
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]
.
How to use fnmatch for filename matching in Python:
fnmatch
module is used for simple filename matching based on Unix shell-style wildcards.import fnmatch file_name = "example.txt" pattern = "*.txt" if fnmatch.fnmatch(file_name, pattern): print("Match found!")
Wildcard pattern matching with fnmatch in Python:
*
for any number of characters, ?
for a single character) in patterns for flexible matching.import fnmatch file_name = "example.txt" pattern = "ex*ple.txt" if fnmatch.fnmatch(file_name, pattern): print("Match found!")
Case-insensitive filename matching with fnmatch:
fnmatchcase
function for case-insensitive filename matching.import fnmatch file_name = "Example.txt" pattern = "example.txt" if fnmatch.fnmatchcase(file_name, pattern): print("Match found!")
Filtering files using fnmatch in Python:
fnmatch.filter
.import fnmatch file_names = ["file1.txt", "file2.txt", "image.jpg", "document.pdf"] pattern = "*.txt" filtered_files = fnmatch.filter(file_names, pattern) print(filtered_files)
Matching multiple patterns with fnmatch in Python:
import fnmatch file_name = "example.txt" patterns = ["ex*.txt", "*.pdf"] if any(fnmatch.fnmatch(file_name, pattern) for pattern in patterns): print("Match found!")
Using fnmatch to find files in a directory in Python:
os.listdir
with fnmatch.filter
to find files in a directory based on a pattern.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)
Customizing filename matching behavior with fnmatch:
fnmatch.translate
function for more advanced patterns.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!")
Comparing fnmatch with regular expressions in Python:
fnmatch
is simpler for basic matching, regular expressions provide more advanced pattern matching capabilities.import re file_name = "example.txt" pattern = "ex.*\.txt" if re.match(pattern, file_name): print("Match found using regular expression!")
Pattern matching and exclusion with fnmatch in Python:
fnmatch.filter
with additional conditions for both pattern matching and exclusion.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)
Recursive file searching with fnmatch in Python:
os.walk
and fnmatch.filter
.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))
Handling special characters in filenames with fnmatch:
re.escape
to ensure accurate matching.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!")