Python List Files In Directory With Extension
Last Updated : Mar 11, 2024
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)
- The os module provided by the code provides a way to interact with the operating system.
- There is a list 'l' that holds all the names of text files found in the current directory.
- "All the text files from a directory:" is printed on the console as an indication that the following code block pertains to text files.
- Using the listdir method from the OS module, all files in the current working directory are searched within a 'for' loop.
- When the file extension ends in '.txt', an 'if' statement checks whether it is a text file.
- Text files are given the letter 'L' as an extension if they are text files.
- There is another iteration that takes place with another 'for' loop on the text files in 'l', a list with only text files.
- 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.