Skip to main content

How to filter files by extension in Python

How to filter files by extension in Python.

Here's a step-by-step tutorial on how to filter files by extension in Python:

Step 1: Import the os module

To work with files and directories, we need to import the built-in os module. This module provides various functions for interacting with the operating system.

import os

Step 2: Define the directory path

Specify the directory path where you want to filter the files. You can either provide an absolute path or a relative path.

directory_path = '/path/to/directory'

Step 3: List all files in the directory

Use the os.listdir() function to get a list of all files and directories present in the specified directory.

files = os.listdir(directory_path)

Step 4: Filter files by extension

Iterate over the list of files and use the os.path.splitext() function to split the file name and extension. Compare the extension with the desired extension using an if statement.

desired_extension = '.txt'  # Change this to the desired extension

filtered_files = []
for file in files:
_, extension = os.path.splitext(file)
if extension == desired_extension:
filtered_files.append(file)

Alternatively, you can use a list comprehension to achieve the same result in a more concise way:

filtered_files = [file for file in files if os.path.splitext(file)[1] == desired_extension]

Step 5: Print or process the filtered files

You can print the filtered file names or perform further processing on them based on your requirements.

for file in filtered_files:
print(file)

That's it! You now have a list of files filtered by their extension.

Here's the complete code:

import os

directory_path = '/path/to/directory'
files = os.listdir(directory_path)

desired_extension = '.txt' # Change this to the desired extension

filtered_files = [file for file in files if os.path.splitext(file)[1] == desired_extension]

for file in filtered_files:
print(file)

Feel free to modify the desired_extension variable to match the extension you want to filter by.