Table of Contents
While dealing with the large number of files, we may come across the scenario where we need to find a file of a particular type. By using python in-built package re, we can easily find the file. Our task is to find the file having a particular extension.
import re def search(ip_file): for fnames in ip_file: search_ext = re.search("\.txt$", fnames) if search_ext: print("File with extension .txt is:", fnames) ip_file = ["py.html", "python.xml", "py.rar", "py.txt", "python.jpg"] search(ip_file)
In the above python code, the regular expression we have used to find .txt file is “\.txt$” where, $ represents that the string is ending with the character before it (i.e. the string ends with .txt). If the search is true, the file name is printed on the screen.