How to Use Regex with os.listdir() in Python?
Last Updated :
12 Mar, 2024
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.
- Filter .txt Files
- Filter .pdf Files
- Filter Files by length
File Structure:

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', ...]
Similar Reads
How to use OS with Python List Comprehension One such module is the 'os' module, which allows interaction with the operating system. When combined with list comprehensions, the 'os' module becomes a potent tool for handling file and directory operations concisely and expressively. In this article, we will see how we can use the os module with
3 min read
Python | Check if string matches regex list Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let's discuss a way in which this task can be performed. Method : Using join regex + loop + re.match() This task can be performed usi
4 min read
How Use Linux Command In Python Using System.Os Using the system module from the os library in Python allows you to interact with the Linux command line directly from your Python script. This module provides a way to execute system commands, enabling you to automate various tasks by integrating Linux commands seamlessly into your Python code. Whe
3 min read
Os.Listdir() is not Working in Python The os.listdir function serves as a fundamental tool for retrieving the contents of a directory. However, users occasionally encounter perplexing situations where the function fails to display all the expected files. This article delves into the intricacies of this phenomenon, exploring the reasons
3 min read
How to Find Index of a Substring in Python In Python, sometimes we need to know where a certain substring appears in a string. To do this, we can find the index (or position) of that substring. The index tells us where the substring is located. Letâs look at some simple ways to find the index of a substring in a string.Using find() methodThe
2 min read
Python | Sort and store files with same extension Have you ever wanted to find any particular file in a folder, but then completely freak out when you find that folder to be a hell of a mess? Well, Python is a rescue here. Using Python OS-module and shutil module, we can organize the files with same extensions and store in separate folders. Look at
2 min read
Python Extract Substring Using Regex Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
2 min read
Uses of OS and Sys in Python In this article, we will see where we use Os and Sys in Python with the help of code examples. What is Os Module?Python OS module in Python furnishes a versatile means of engaging with the operating system. It facilitates a range of operations, including the creation, deletion, renaming, movement, a
4 min read
Python Regex - Program to accept string starting with vowel Prerequisite: Regular expression in PythonGiven a string, write a Python program to check whether the given string is starting with Vowel or Not.Examples: Input: animal Output: Accepted Input: zebra Output: Not Accepted In this program, we are using search() method of re module.re.search() : This me
4 min read
re.split() in Python The re.split() method in Python is used to split a string by a pattern (using regular expressions). It is part of the re-module, which provides support for working with regular expressions. This method is helpful when we need to split a string into multiple parts based on complex patterns rather tha
3 min read