List all files of certain type in a directory using Python
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
- Using os. walk()
- Using os. listdir()
- Using glob. glob()
Using os.walk() function
In python programming, there are different os modules which enable several methods to interact with the file system. As mentioned above it has 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 is the files under the root directory and it’s a subdirectory.
Using os. listdir() function
Os has another method which 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.
Using glob. glob() function:
In the previous examples, we have to iterate over a list of files in a directory having name match with 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 as 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.
glob.glob(path name, recursive=True)