Open In App

How to Use Regex with os.listdir() in Python?

We are given a file path and our task is to find out the usage of regex with os.listdir() in Python by using that path and files inside that directory. In this article, we will see the usage of Regex with os.listdir() in Python with code examples.

Regex with os.listdir() in Python

In Python, the os.listdir() function is used to list the files and directories in a specified path. When combined with regular expressions (regex), you can filter and retrieve specific files based on a pattern. By using regex in os.listdir(), you can customize the file selection criteria, allowing you to match filenames that adhere to a particular pattern or contain specific characters. For using the Regex In Os.Dir In Python first we need to import it using the below command

Syntax:

import os
import re

How to Use Regex with os.listdir() in Python?

Below, are the code examples of using Regex In Os.Dir In Python.

File Structure:

hhhhh

Filter .txt Files using Regex with os.listdir

In this example, below Python code uses the `os.listdir()` function to iterate through files in the specified directory (`path`). It employs the `re.search()` method with a regex pattern to filter and print filenames matching the specified criteria (in this case, files ending with ".txt").

Python3
import os
import re

path = "/your/directory/path"
pattern = r".*\.txt$"  # Match all files ending with ".txt"

for filename in os.listdir(path):
    if re.search(pattern, filename):
        print(filename)

Output:

file1.txt
file2.txt
# (assuming other .txt files exist)

Filter .pdf Files using Regex with os.listdir

In this example, below code uses the `os.listdir()` function to iterate through files in the specified directory (`directory_path`). It employs a compiled regex pattern (`re.compile()`) to match and print filenames adhering to the specified criteria (in this case, files starting with "report_" and ending with ".pdf").

Python3
import os
import re

directory_path = "gfg"
pattern = re.compile(r'report_.*\.pdf')  

for filename in os.listdir(directory_path):
    if pattern.match(filename):
        print(os.path.join(directory_path, filename))

Output:

report_2023.pdf
report_monthly.pdf
# (assuming other matching files exist)

Filter Files by length using Regex with os.listdir

In this example, below Python code defines a function filter_filenames_by_length that uses the os.listdir() function to iterate through files in the specified directory (directory_path). It employs a regex pattern (pattern_3) to match filenames with lengths ranging from 5 to 10 characters (inclusive).

Python3
import os
import re

# Replace with your actual directory path
directory_path = "/path/to/your/directory"

# Regex pattern to match filenames with 5 to 10 characters (inclusive)
pattern_3 = r"^.{5,10}$"


def filter_filenames_by_length(directory_path, pattern):
    matching_files = []
    for filename in os.listdir(directory_path):
        if re.match(pattern, filename):
            matching_files.append(filename)
    return matching_files


matching_files_3 = filter_filenames_by_length(directory_path, pattern_3)
print("Filenames with length between 5 and 10 characters:\n", matching_files_3)

Output:

Filenames with length between 5 and 10 characters:
 ['report.pdf', 'image.jpg', ...]
Article Tags :