List all files of certain type in a directory using Python


Python's flexible features and strong libraries make manipulating files and directories a breeze. Python has you covered for generating, updating, and retrieving data from files and folders. One such typical need is a directory listing of all files of a specific type. This tutorial will walk you through the procedure using real-world examples to demonstrate Python's proficiency with filesystem operations.

Introduction to Python's Os and Glob Libraries

The standard Python library has a number of modules that can manage filesystem operations. The os and glob modules are two examples of well-known modules.

  • os module − Python's os module offers tools for communicating with the operating system. It offers operations for adding, deleting, and browsing directories, which is useful for file and directory manipulation.

  • glob module  Another effective tool is the glob module, which uses the Unix shell's rules to locate all the pathnames that match a certain pattern. Given that it enables wildcard characters like * and?, it is ideal for our objective.

Let's dive into the examples to understand their usage better.

Example 1: Using Os and Fnmatch Modules

Here, we'll use the os and fnmatch modules in Python to list every.txt file present in a directory.

import os
import fnmatch

def list_files(directory, filetype):
   for file in os.listdir(directory):
      if fnmatch.fnmatch(file, filetype):
         print(file)

list_files('/home/user/documents', '*.txt')

The os.listdir() function in this code snippet displays a list of every file and directory in the specified directory. The fnmatch() function of the fnmatch module then determines if each file matches the specified filetype pattern. The file name is printed if the file type matches.

Example 2: Using Glob Module

Let's now list every.jpg image file present in a directory using the glob module.

import glob

def list_files(directory, filetype):
   for file in glob.glob(f"{directory}/{filetype}"):
      print(file)

list_files('/home/user/images', '*.jpg')

The glob.glob() function is used in this example to return a list of paths that match the pathname pattern. The directory path and the filetype are combined in the f-string. The.jpg files in the directory are then printed out by the function.

Example 3: Recursive Search Using Glob Module

Using the glob module, we can also conduct a recursive search for files of a specific kind within a directory and its subdirectories. Let's look for all.png picture files, for example.

import glob

def list_files(directory, filetype):
   for file in glob.glob(f"{directory}/**/{filetype}", recursive=True):
      print(file)

list_files('/home/user/images', '*.png')

The ** in the path string of this code snippet instructs glob to perform a recursive search in all folders and subdirectories. The recursive feature is enabled with the recursive=True option.

Example 4: List All Python Files

The os and fnmatch modules can be used in the following way to locate and list every Python.py file in a particular directory −

import os
import fnmatch

def list_files(directory, filetype):
   for file in os.listdir(directory):
      if fnmatch.fnmatch(file, filetype):
         print(file)

list_files('/home/user/my_python_projects', '*.py')

This will list all of the directory's.py files' names.

Example 5: Using Os.walk for a Recursive Search

Additionally, we can use os.walk() to perform a recursive search. This function walks a directory tree either top-down or bottom-up to create file names.

import os
import fnmatch

def list_files(directory, filetype):
   for dirpath, dirnames, files in os.walk(directory):
      for file in files:
         if fnmatch.fnmatch(file, filetype):
            print(os.path.join(dirpath, file))

list_files('/home/user/projects', '*.txt')

The directory tree is walked over in this script using the os.walk() function. Each file is compared to the desired filetype using the fnmatch.fnmatch() function, and the full path of the matched files is obtained using os.path.join().

Conclusion

Many coding scenarios call for listing all files of a particular kind in a directory, and Python's broad collection of modules, such os and glob, offers an easy way to do this. The numerous real-world examples provided in this article make it crystal obvious how to use these modules to list files in a directory as well as to do a recursive search in the directory and any subdirectories.

It's crucial to have the ability to work with files and directories in your programming toolbox. These abilities are in handy for organising project files, looking through log files, and even automating system functions. Keep investigating with these routines to find even more of Python's robust filesystem management features.

Updated on: 18-Jul-2023

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements