List all files of certain type in a directory using Python
Last Updated :
30 Sep, 2022
In python, there are several built-in modules and methods for file handling. These functions are present in different modules such as os, glob, etc. This article helps you find out many of the functions in one place which gives you a brief knowledge about how to list all the files of a certain type in a directory by using Python programming.
So there are three certain extensions such as
Directory used:
List all files of a certain type using os.walk() function
In python programming, there are different os modules that enable several methods to interact with the file system. As mentioned above it has a walk() function which helps us to list all the files in the specific path by traversing the directory either by a bottom-up approach or by a top-down approach and return 3 tuples such as root, dir, files
Here root is the root directory or root folder, dir is the subdirectory of the root directory and files are the files under the root directory and it’s a subdirectory.
Syntax of walk() function
os.walk(r’pathname’)
Python3
import os
for root, dirs, files in os.walk(r 'F:' ):
for file in files:
if file .endswith( '.png' ):
print (os.path.join(root, file ))
|
Output:
List all files of a certain type using os. listdir() function
Os has another method that helps us find files on the specific path known as listdir(). It returns all the file names in the directory specified in the location or path as a list format in random order. It excludes the ‘.’ and ‘..’ if they are available in the input folder.
Syntax of listdir() function:
os.listdir(r’pathname’)
Python3
import os
for file in os.listdir(r 'F:' ):
if file .endswith( ".png" ):
print (os.path.join(r 'F:' , file ))
|
Output:
List all files of a certain type using glob. glob() function
In the previous examples, we have to iterate over a list of files in a directory having names that match the particular extensions or patterns. But glob modules gives the facility to find a list of files with particular extensions or pattern. This function has two parameters one is path-name with a specific pattern which filters out all the files and returns the files as a list. Another Parameter named recursive by default it is off means false. When its value is true then the function searches its directory along with its subdirectory. All wild cards are allowed here like’?’,’*’ etc.
Syntax of glob() function:
glob.glob(path name, recursive=True)
Python3
import glob
import os
for file in glob.glob(r 'F:' + '**/*.png' , recursive = True ):
print (os.path.join(r 'F:' , file ))
|
Output:
Share your thoughts in the comments
Please Login to comment...