How to find all files in a directory with specific extension using Python

Whenever we need to check if file with specific extension exists in a directory or get list of files with specific extension from a directory, it can be done using python. Here is simple program for doing the same.

There are three ways to do this using python

  1. os.walk
  2. os.listdir
  3. glob.glob

All three methods are demonstrated in below program

################################################################################################
# name: file_with_specific_extension_in_directory.py
# desc:
# date: 2019-03-30
# Author: conquistadorjd
################################################################################################
import os
import glob
print("*** Program Started ***")
dir_name = 'C:/sample/'
matches = []
for root, dirnames, filenames in os.walk(dir_name):
for filename in filenames:
# if filename.endswith(('.txt', '.MOV', '.avi', '.mpg')): ## Checking for multiple extenstions
if filename.endswith('.txt'):
matches.append(filename)
print("List of Files using os.walk:", matches)
matches = []
filenames = os.listdir(dir_name)
for filename in filenames:
# if filename.endswith(('.txt', '.MOV', '.avi', '.mpg')): ## Checking for multiple extenstions
if filename.endswith('.txt'):
matches.append(filename)
print("List of Files using listdir:", matches)
# filenames = glob.glob(dir_name+'*.txt') ## This will return file name with complete path name as well
matches = [os.path.basename(x) for x in glob.glob(dir_name+'*.txt')] ## This will return only file name
print("List of Files using glob :", matches)
print("*** Program Completed ***")

Output of the program

*** Program Started ***
List of Files using os.walk: ['file3.txt', 'list_to_file_in_directory.txt', 'test.txt']
List of Files using listdir: ['file3.txt', 'list_to_file_in_directory.txt', 'test.txt']
List of Files using glob : ['file3.txt', 'list_to_file_in_directory.txt', 'test.txt']
*** Program Completed ***

 

Leave a Reply

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