Skip to content

Find all files in a directory with extension .txt in Python

Here is a code snippet that uses the os and glob modules to find all files in a directory with the extension '.txt':

Find all files in a directory with extension .txt in Python using os.path method

python
import os
from glob import glob

directory = '/path/to/dir'
txt_files = glob(os.path.join(directory, '*.txt'))
print(txt_files)

The os.path.join() function is used to combine the directory path and the file extension to form the pattern that glob() searches for. The glob() function returns a list of file paths that match the pattern.

You can also use the os.listdir() to get the list of all files in the directory and filter the files based on the extenstion like this

Find all files in a directory with extension .txt in Python using os.listdir method

python
import os

directory = '/path/to/dir'
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]
print(txt_files)

You can also use the os.scandir() function for faster directory scanning, which provides a more efficient way of traversing a directory tree.

Find all files in a directory with extension .txt in Python using os.scandir method

python
import os

directory = '/path/to/dir'
txt_files = [f.name for f in os.scandir(directory) if f.name.endswith('.txt') and f.is_file()]
print(txt_files)

Dual-run preview — compare with live Symfony routes.