All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Python List Files In Directory With Extension

Last Updated : Mar 11, 2024

Python List Files In Directory With Extension

In this article we will show you the solution of python list files in directory with extension, when a developer performs operations on a folder, it is often necessary to prune the folder for files with a specific extension, for example, listing the files in the folder with the specified extension before performing any actions on them.

For example, you would copy a text file from one place to another using a .txt extension.

When this happens, it is necessary to find all files within a directory by using aList and giving them the .txt extension.

The purpose of this article is to demonstrate how you can find files with the extension .txt in a directory using Python.

We will now discuss the idea of python list files in the directory with extension with an example.

Step By Step Guide On Python List Files In Directory With Extension :-

# Importing the os module
import os
l = []
print("TalkersCode text files of directory:")
for f in os.listdir("."):
    if f.endswith('.txt'):
        l.append(f)
for file in l:
    print(file)
  1. The os module provided by the code provides a way to interact with the operating system.
  2. There is a list 'l' that holds all the names of text files found in the current directory.
  3. "All the text files from a directory:" is printed on the console as an indication that the following code block pertains to text files.
  4. Using the listdir method from the OS module, all files in the current working directory are searched within a 'for' loop.
  5. When the file extension ends in '.txt', an 'if' statement checks whether it is a text file.
  6. Text files are given the letter 'L' as an extension if they are text files.
  7. There is another iteration that takes place with another 'for' loop on the text files in 'l', a list with only text files.
  8. Using the 'print' function, the file name is printed on the console inside the loop.

Conclusion :-

As a result, we have successfully learned how to list files in the directory with an extension in Python.

The following post will show you how to list all files in a directory using the OS listdir function, how to traverse folders and get all file names in a directory, and how to use glob to get specific paths to files.

I hope this article on python list files in directory with extension helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Anjali

Experienced Computer Programmer with a broad range of experience in technology. Strengths in application development and Object Oriented architecture design, front end programming, usability and multimedia technology. Expert in coding languages such as C, C++ Java, JavaScript, PHP and more.

Follow Anjali On Linkedin 🡪