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()
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 # traverse whole directory for root, dirs, files in os.walk(r 'F:' ): # select file name for file in files: # check the extension of files if file .endswith( '.png' ): # print whole path of files 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 # return all files as a list for file in os.listdir(r 'F:' ): # check the files which are end with specific extension if file .endswith( ".png" ): # print path name of selected files 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 # glob.glob() return a list of file name with specified pathname for file in glob.glob(r 'F:' + '**/*.png' , recursive = True ): # print the path name of selected files print (os.path.join(r 'F:' , file )) |
Output: