Python find files with extensions

Python list Files in Directory with Extension txt

In this Python tutorial, we will see how to list all files of a directory having a specific extension.

Sometimes we need to list files having a specific extension before performing any operation on them. For example, if you wanted to copy only text files from one location to another. In this case, we need to make sure we are only looking for files having a .txt extension.

We will use the following three methods.

Table of contents

How to list files in directory with extension txt

A file extension, or filename extension, is a suffix at the end of a file. It comes after the period. Extension specifies a file type such as text, CSV file, pdf, or image file. For example, for a text file, it is txt . For image file it is jpg , jpeg , or bmp .

Here are the steps to get the list of files having the txt extension using a glob module.

  1. Import glob module The glob module, part of the Python Standard Library, is used to find the files and folders whose names follow a specific pattern. The searching rules are similar to the Unix Shell path expansion rules.
  2. Construct a pattern to search for the files having the specific extension For example, directory_path/*.txt to list all text files present in a given directory path. Here the * means file name can be anything, but it must have a txt extension.
  3. Use glob() method The gob.glob(pathname) method returns a list of files that matches the path and pattern specified in the pathname argument. in this case, it will return all text files.
Читайте также:  Java get all constructors

Example: list files in directory with extension txt

The following text files are present in my current working directory.

sales.txt profit.txt samples.txt

Example 1: List all txt files present in the ‘account’ directory.

import glob # absolute path to search all text files inside a specific folder path = r'E:/demos/files_demos/account/*.txt' files = glob.glob(path) print(files) 
['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt']

If you want to list files from a current directory the use glob.glob(‘./*.txt’) .

Note: This solution is fast because it only looks for a specific pattern instead of traversing the entire directory file by file to check if it has a specific extension, resulting in performance benefits.

Os module to list files in directory with extension

This module helps us to work with operating system-dependent functionality in Python. The os module provides functions for interacting with the operating system.

  • Use the os.listdir(‘path’) function to get the list of all files of a directory. This function returns the names of the files and directories present in the directory.
  • Next, use a for loop to iterate all files from a list.
  • Next, use the if condition in each iteration to check if the file name ends with a txt extension. If yes, add it to the final list
import os # folder path dir_path = r'E:\account' # list to store files res = [] # Iterate directory for file in os.listdir(dir_path): # check only text files if file.endswith('.txt'): res.append(file) print(res)
['profit.txt', 'sales.txt', 'sample.txt']

Note: This solution is slow because it traverses the entire directory file by file to check if it has a specific extension, resulting in performance overhead if the directory contains many files. So I suggest you use the first solution, i.e., glob module.

list files in directory and subdirectories with extension txt

We can use the following two approaches: –

Glob module to list files from subdirectories with txt extension

Set the recursive attribute of a glob() method to True to list text files from subdirectories.

Use Python 3.5+ to find files recursively using the glob module. If you are using the older version of Python, then use the os.walk() method.

The glob module supports the ** directive. If you want it recursive you can use glob.glob(‘**/*.txt’) and set a recursive flag to True , the glob() method parses the given path and looks recursively in the directories.

import glob # absolute path to search all text files inside a specific folder path = r'E:/account/**/*.txt' files = glob.glob(path, recursive=True) print(files)
['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt', 'E:/account\\reports_2021\\december_2021.txt']

os.walk() to list files in directory and subdirectories with extension txt

It is a recursive function, i.e., Every time the generator is called it creates a tuple of values (current_path, directories in current_path, files in current_path) and it will follow each directory recursively to get a list of files and directories until no further sub-directories are available from the initial directory.

  • Call the os.walk(»path’) function. It will yield two lists for each directory it visits. The first list contains files, and the second list includes directories.
  • Next, Iterate the list of files using a for loop
  • Next, use the if condition in each iteration to check if the file name ends with a txt extension. If yes, add it to the final list.
import os # list to store txt files res = [] # os.walk() returns subdirectories, file from current directory and # And follow next directory from subdirectory list recursively until last directory for root, dirs, files in os.walk(r"E:\demos\files_demos\account"): for file in files: if file.endswith(".txt"): res.append(os.path.join(root, file)) print(res) 
['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt', 'E:/account\\reports_2021\\december_2021.txt']

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

Читайте также:  №3-3

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

How To Find files with Certain Extension using Python

We know how to find files and do operations on that file using the file handling methods. But when we need to do certain operations on a file with a specific file extension like .txt , .PNG , .JPG , or .py , we need to find that file.

As we all know there are several methods to find the files, but in this tutorial, we will learn to find the files with certain extensions using the endswith() function, comprehension method, and the several methods present in the os module and glob module.

The endswith() is an in-built function that returns True in this case, if the string ends with a particular specified suffix; else it will return F alse . The glob.glob() function returns the file name with a specified pattern.

Example: Finding files in a directory using the listdir() Function

The below example shows how to find files in the directory using the listdir() function.

# Lists all files #import os module import os # Specifies the path in path variable path="C:\my_dir" for x in os.listdir(path): print(x)

Once we run the program we will get the following output.

instance_var_examples.py
mp4_1.mp4
mp4_5.mp4
practice.py
practice1.py
write opeartion.png

Читайте также:  How to create int array in java

Example: Finding file using the endswith() Function

The below example shows how to find files in the directory with certain extension using the listdir() function and the endswith() function.

# Finding files with extension using for loop #import os module import os # Specifies the path in path variable path="C:\my_dir" for i in os.listdir(path): # List files with .py if i.endswith(".py"): print("Files with extension .py are:",i) 

Once we run the program we will get the following output.

Files with extension .py are: instance_var_examples.py
Files with extension .py are: practice.py
Files with extension .py are: practice1.py
Files with extension .py are: Static_var.py
Files with extension .py are: variables_2.py
Files with extension .py are: var_1.py

Example: Finding files with a certain extension using the comprehension

The below example shows how to find files in the directory with a certain extension using the listdir() function and the endswith() function with the comprehension method.

# Using comprehension method import os path = 'C:\my_dir' files = [x for x in os.listdir(path) if x.endswith('.py')] print(files)

Once we run the program we will get the following output.

[‘instance_var_examples.py’, ‘practice.py’, ‘practice1.py’, ‘Static_var.py’, ‘variables_2.py’, ‘var_1.py’]

Example: Finding files with a certain extension using the glob and os Module

The below example shows how to find files in the directory with a certain extension using the glob and os module.

# Another method using glob and os module #import glob and os module import glob import os os.chdir("C:\my_dir") for file in glob.glob("*.py"): print(file)

Once we run the program we will get the following output.

instance_var_examples.py
practice.py
practice1.py
Static_var.py
variables_2.py
var_1.py

Conclusion

In this tutorial, we learned how to find the files with specified extensions using the python in-built function endswith() and the glob and os module.

Источник

Оцените статью