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':

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.

Watch a course Python - The Practical Guide

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

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.

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)