Write a Python Program to Find All File with .txt Extension Present Inside a Directory

As a Python programmer, you may often need to find all files with a specific extension within a directory.

In this tutorial, we’ll look at how to use Python to find all files with a “.txt” extension present inside a directory.


Python provides a standard library module called os, which provides a way to interact with the file system.

We can use the os module to list all files and directories within a directory.

Then we can loop through the list of files and check if the file has a “.txt” extension.

Here’s the Python code that lists all “.txt” files within a directory:

import os

directory_path = "/path/to/directory"

for filename in os.listdir(directory_path):
    if filename.endswith(".txt"):
        print(filename)

The above code first defines the directory_path variable to store the path of the directory that we want to search for “.txt” files.

Then it loops through all the files and directories within that directory using the os.listdir() function.

For each file, it checks if the filename ends with “.txt” using the str.endswith() method.

If the file has a “.txt” extension, it prints the filename.

Note that this code only lists the filenames.

If you want to access the content of the “.txt” files, you can use the open() function to open the file and read its contents.


In conclusion, finding all files with a specific extension within a directory is a common task in Python programming.

By using the os module, we can easily list all files within a directory and filter them by their extension.