How do I list all files of a directory in Python?


Among several file-handling operations, the need to list all files in a directory is a common scenario encountered in Python, and it's quite straightforward. Python offers a utilitarian module called os that provides functions to work with the operating system, the directories, and the files seamlessly. We will cover different strategies and ways of listing all files in a directory using practical code examples followed by detailed explanations to help you understand the concept behind the same.

Using os.listdir() to List Files

To list all files in a directory, you can use the os.listdir() function. Let's walk through the steps with a code example:

Example

In this example, we first import the os module. The list_files_in_directory() function takes directory_path as its parameter, where you can specify the path of the directory you want to list files from.

Using os.listdir(directory_path), we get a list of all files and directories present in the specified directory. Then, we filter out only the files from this list by checking each element's existence with os.path.isfile().

Finally, the function returns the list of files found in the directory. If the directory does not exist, we handle the FileNotFoundError and print an error message.

With this code snippet, you can easily list all files in a directory using Python, streamlining your file management tasks and making your coding experience even more delightful.

import os

def list_files_in_directory(directory_path):
   try:
      # Use os.listdir() to get a list of all files in the directory
      files_list = os.listdir(directory_path)

      # Filter out directories from the list, keeping only files
      files_list = [file for file in files_list if os.path.
isfile(os.path.join(directory_path, file))]

      return files_list

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' 
does not exist.")
      return []

# Replace 'directory_path' with the path of the 
directory you want to list files from
directory_path = '/path/to/your/directory'
files_in_directory = list_files_in_directory(directory_path)

if files_in_directory:
   print("Files in the directory:")
   for file_name in files_in_directory:
      print(file_name)
else:
   print("No files found in the directory.")

Output

For a certain directory, the following was the output

Files in the directory:
baz.txt
bar.txt

Using os.listdir() to List Files

Example

We, at first, begin by importing the os module that provides several useful functions and methods.

The list_files_in_directory() function accepts directory_path as its argument. The directory_path represens the path to the target directory.

A list of all files and directories in the target directory is obtained by using the os.listdir(directory_path) function.

We iterate through each item and check if it is a file by deploying os.path.isfile(); we retrieve only the files and load them in the files_list.

If the specific directory doesn't exist, the FileNotFoundError is caught and an error message is displayed.

import os

def list_files_in_directory(directory_path):
   try:
      # Get a list of all files and directories
 in the specified directory
      all_items = os.listdir(directory_path)

      # Filter out only the files from the list
      files_list = [item for item in all_items if 
os.path.isfile(os.path.join(directory_path, item))]

      return files_list

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' 
does not exist.")
      return []
# Replace 'directory_path' with the path of the directory you want to list files from
directory_path = '/path/to/your/directory'
files_in_directory = list_files_in_directory(directory_path)

if files_in_directory:
   print("Files in the directory:")
   for file_name in files_in_directory:
      print(file_name)
else:
   print("No files found in the directory.")

Output

For a certain directory, the following was the output

Files in the directory:
baz
bar

Using os.scandir() for Efficient Listing

Example

In this current example, os.listdir() is replaced with os.scandir() to achieve a more productive listing of files in the directory.

By making use of os.scandir(directory_path), we efficiently iterate through the directory entries; there is no need to explicitly close the directory afterward.

It is checked if each entry in entries is a file by making use of entry.is_file(); and if it is found that the entry is a file, we add its name to the files_list.

As seen before, we notify the occurrence of the FileNotFoundError with a corresponding error message.

import os

def list_files_in_directory(directory_path):
   try:
      # Use os.scandir() for a more efficient listing
      with os.scandir(directory_path) as entries:
         files_list = [entry.name for entry in 
entries if entry.is_file()]

      return files_list

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' 
does not exist.")
      return []

# Replace 'directory_path' with the path of 
the directory you want to list files from
directory_path = '/path/to/your/directory'
files_in_directory = list_files_in_directory(directory_path)

if files_in_directory:
   print("Files in the directory:")
   for file_name in files_in_directory:
      print(file_name)
else:
   print("No files found in the directory.")

Output

For a certain directory, the following was the output

Files in the directory:
baz
bar

Recursive Listing with os.walk()

Example

In this example, we utilize os.walk() to make a recursive list of files within subdirectories as well.

The os.walk(directory_path) function gives as output a generator that has tuples containing the root directory, subdirectories, and files within that directory.

Through each tuple iteration is done, and for each file in the files list, the full file path is created using os.path.join() and the file is added to the files_list.

This makes it possible for us to obtain a complete list of all files, including those present in subdirectories.

import os

def list_files_in_directory(directory_path):
   try:
      # Use os.walk() to get a recursive listing of all files
      files_list = []
      for root, dirs, files in os.walk(directory_path):
         for file in files:
            files_list.append(os.path.join(root, file))

      return files_list

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' 
does not exist.")
      return []
# Replace 'directory_path' with the path of 
the directory you want to list files from
directory_path = '/path/to/your/directory'
files_in_directory = list_files_in_directory(directory_path)

if files_in_directory:
   print("Files in the directory:")
   for file_name in files_in_directory:
      print(file_name)
else:
   print("No files found in the directory.")

Output

For a certain directory, the following was the output

Files in the directory:
/content/foo/baz
/content/foo/bar

Using pathlib.Path() for Modern Listing

Example

In this final example, we embrace the power of pathlib.Path() for turbocharged file listing in Python.

pathlib.Path(directory_path) helps create a Path object; this allows us to work with the directory and its contents.

We get an iterator of all directory entries ,i.e., files and directories by making use of path.iterdir() to.

While using file.is_file(), we make sure to check if each entry is a file, and if true, we extract its name and add it to the files_list.

from pathlib import Path

def list_files_in_directory(directory_path):
   try:
      # Use pathlib.Path() for modern file listing
      path = Path(directory_path)
      files_list = [file.name for file in path.iterdir() if file.is_file()]

      return files_list

   except FileNotFoundError:
      print(f"Error: The directory '{directory_path}' does not exist.")
      return []
# Replace 'directory_path' with the path of the directory you want to list files from
directory_path = '/path/to/your/directory'
files_in_directory = list_files_in_directory(directory_path)

if files_in_directory:
   print("Files in the directory:")
   for file_name in files_in_directory:
      print(file_name)
else:

   print("No files found in the directory.")

Output

For a certain directory, the following was the output

Files in the directory:
baz
bar

Aided by these four code examples and their explanations, you now have a versatile toolkit at your disposal to list files in a directory using Python. It does not matter whether you opt for the customary approach with os.listdir(), a more productive listing with os.scandir(), a recursive search with os.walk(), or a cutting-edge approach with pathlib.Path(), either way, Python offers a plethora of options to cater to your specific needs.

To summarize, the ability and skill of listing files in a directory is a valuable tool that simplifies file management tasks and enhances code organization. Python's flexibility and variety of tools make it possible for us to effortlessly navigate directories and extract the information we seek. As you continue your Python journey, you should keep honing your skills and exploring the vast possibilities of this versatile language.

Updated on: 28-Jul-2023

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements