![]() |
VOOZH | about |
In Python, you can efficiently identify files with a specific extension from a list of different file types using the built-in re module. This allows you to perform pattern matching without installing any external libraries. This article demonstrates how to find files with a particular extension (for example .xml) using regex.
1. Define the regex pattern: To match .xml files, use the pattern: \.xml$
2. Use re.search(): The re.search() function checks for a match anywhere in the string and returns a match object if found, otherwise, it returns None.
3. Loop through the files: Check each file name against the regex pattern and print the files that match the pattern.
Output
The file ending with .xml is: geeks.xml
Explanation:
Note: This method works for any file extension by simply changing the regex pattern.