Program to search file having particular extension using regex

by | Dec 26, 2020 | Python Programs

Home » Python » Python Programs » Program to search file having particular extension using regex

Introduction

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.

Program

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)

Output

search file having particular extension

Explanation

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.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

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

Author