Python – List files in directory with extension
Last Updated :
14 Feb, 2023
In this article, we will discuss different use cases where we want to list the files with their extensions present in a directory using python.
Modules Used
- os: The OS module in Python provides functions for interacting with the operating system.
- glob: In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The pattern rules of glob follow standard Unix path expansion rules. It is also predicted that according to benchmarks it is faster than other methods to match pathnames in directories.
Directory Structure in use:

Directory Structure Root View

Directory Files Visual Representation
Method 1: Using `os` module
This module provides a portable way of using operating system-dependent functionality. The method os.listdir() lists all the files present in a directory. We can make use of os.walk() if we want to work with sub-directories as well.
Syntax:
os.listdir(path = ‘.’)
Returns a list containing the names of the entries in the directory given by path.
Syntax:
os.walk(top, topdown=True, onerror=None, followlinks=False)
Generates the file names in a directory tree by walking the tree either top-down or bottom-up.
Example 1: List the files and directories present in root/home/project
Python
import os
list_1 = os.listdir(path = r "root/home/project" )
print (list_1)
list_2 = os.listdir(path = r "root/home/project" )
for val in list_2:
if "." not in val:
list_2.remove(val)
print (list_2)
|
Example 1.5: List only the files, by using os.path.isfile function.
Python3
import os
print ( "Python Program to print list the files in a directory." )
Direc = input (r "Enter the path of the folder: " )
print (f "Files in the directory: {Direc}" )
files = os.listdir(Direc)
files = [f for f in files if os.path.isfile(Direc + '/' + f)]
print ( * files, sep = "\n" )
|
Output :
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
Example 2: List all the subdirectories and sub-files present in root/home/project
Python
import os
all_files = list ()
all_dirs = list ()
for root, dirs, files in os.walk( "root/home/project" ):
all_files.extend(files)
all_dirs.extend(dirs)
print (all_files)
print (all_dirs)
|
Output:
[‘charter.xlsx’, ‘timeline.jpg’, ‘report.txt’, ‘workbook.pdf’, ‘trigger.sql’, ‘schema_template.py’, ‘sqlalchemy_models.py’, ‘info.log’, ‘README.md’, ‘requirements.txt’, ‘main.py’]
[‘documents’, ‘code’, ‘database_models’]
Method 2: Using `glob` module
The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. We will use glob.glob() function to achieve our task. The idea behind Unix shell-like means that we can provide Unix shell-like patterns for searching files.
Syntax:
glob.glob(pathname, *, recursive=False)
Return a list of pathnames that match pathname, which must be a string containing a path specification.
The ‘*‘ means that it will match all the items returned by similar to os.listdir() method.
Example 1: Get all the directories and files in root/home/project/code
Python
import glob
list_ = glob.glob(r "root/home/project/code/*" )
print (list_)
|
Output:
[‘database_models’, ‘README.md’, ‘requirements.txt’, ‘main.py’]
Example 2: Get all the python (.py) files in root/home/project/code/database_models
Python
import glob
list_ = glob.glob(r "root/home/project/code/database_models/*.py" )
print (list_)
|
Output:
[‘schema_template.py’, ‘sqlalchemy_models.py’]
Similar Reads
Find all the Files in a Directory with .txt Extension in Python
Directory traversal is a common operation performed by file locator in Operating Systems. The operating system offers elaborate methods for streamlining the search process and the choice to search for a selected filename/extension. This article will teach you how to find all the files in a directory
5 min read
Python - List Files in a Directory
Sometimes, while working with files in Python, a problem arises with how to get all files in a directory. In this article, we will cover different methods of how to list all file names in a directory in Python. Table of Content What is a Directory in Python?How to List Files in a Directory in Python
9 min read
Python - Get list of files in directory with size
In this article, we are going to see how to extract the list of files of the directory along with its size. For this, we will use the OS module. OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a
9 min read
Python | Passing Filenames to Extension in C
Filename has to be encoded according to the systemâs expected filename encoding before passing filenames to C library functions. Code #1 : To write an extension function that receives a filename static PyObject* py_get_filename(PyObject* self, PyObject* args) { PyObject* bytes; char* filename; Py_ss
2 min read
Listing out directories and files in Python
The following is a list of some of the important methods/functions in Python with descriptions that you should know to understand this article. len() - It is used to count number of elements(items/characters) of iterables like list, tuple, string, dictionary etc. str() - It is used to transform data
6 min read
List all Files with Specific Extension in R
R programming language contains a wide variety of method to work with directory and its associated sub-directories. There are various inbuilt methods in R programming language which are used to return the file names with the required extensions. It can be used to efficiently locate the presence of a
3 min read
Change File Extension In Python
Changing file extensions in Python can be a common task when working with files. Whether you need to modify file types for compatibility, organize your files, or perform some other operation, Python provides several methods to achieve this. In this article, we will explore four different methods to
3 min read
Python - Get list of files in directory sorted by size
In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows: Using os.listdir(
3 min read
Check if a File or Directory Exists in Python
To check how to check if a Directory Exists without exceptions in Python we have the following ways to check whether a file or directory already exists or not. Table of Content OS ModuleUsing os.path.exists()Using os.path.isfile()Using os.path.isdir()Pathlib ModuleUsing pathlib.Path.exists()OS Modul
4 min read
Python List All Files In Directory And Subdirectories
Listing all files in a directory and its subdirectories is a common task in Python, often encountered in file management, data processing, or system administration. As developers, having multiple approaches at our disposal allows us to choose the most suitable method based on our specific requiremen
5 min read