Python - List Files in a Directory
Last Updated :
20 Dec, 2024
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.
We will cover two modules and their respective functions for this tutorial on listing file names and details in a directory.
What is a Directory in Python?
A Directory, sometimes known as a folder, is a unit organizational structure in a computer's file system for storing and locating files or more folders. Python now supports several APIs to list the directory contents. For instance, we can use the Path.iterdir, os.scandir, os.walk, Path.rglob, or os.listdir functions.
Directory Structure: gfg

How to List Files in a Directory in Python
There are multiple ways of listing all the files in a directory. In this article, we will discuss the below modules and their functions to fetch the list of files in a directory. We will cover a total of 5 ways with examples to check the list of files in a directory.
List Files in a Directory Using Os Module in Python
We can use these 3 methods of the OS module, to get a list of files in a directory.
- os.listdir() Method
- os.walk() Method
- os.scandir() Method
Get the list of files using os.listdir() method
os.listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory. Beyond the first level of folders, os.listdir() does not return any files or folders.
Example 1: Get a list of all files in a directory
In this example, the os module is imported to interact with the operating system. The listdir function is used to obtain a list of all files and directories in the specified path ("C://Users//Vanshi//Desktop//gfg"). The result is then printed, displaying the names of files and directories present in the specified location.
Python
# import OS module
import os
# Get the list of all files and directories
path = "C://Users//Vanshi//Desktop//gfg"
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# prints all files
print(dir_list)
Output:

Example 2: Get all the files and no folders
In this example, the Python program prompts the user for a folder path, and lists and prints the files in that directory, utilizing the os module for directory interaction and filtering files from the obtained list.
Python
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)
# Filtering only the files.
files = [f for f in files if os.path.isfile(Direc+'/'+f)]
print(*files, sep="\n")
Example 3: Get only '.txt' files from the directory
In this example, the Python script utilizes the os module to iterate through files in the current directory. It selectively prints only the names of files ending with ".txt," effectively listing text files present in the directory.
Python
# import OS
import os
for x in os.listdir():
if x.endswith(".txt"):
# Prints only text file present in My Folder
print(x)
Output:

Access files in a Directory tree using os.walk() method
OS.walk() generates file names in a directory tree. This function returns a list of files in a tree structure. The method loops through all of the directories in a tree.
Example: Get only '.txt' files in a directory
In this example, the Python script uses the os module to traverse through files in the specified directory ("C://Users//Vanshi//Desktop//gfg") and its subdirectories. It identifies and prints the names of files with a ".txt" extension, populating the list variable with the desired text files.
Python
# import OS module
import os
# This is my path
path = "C://Users//Vanshi//Desktop//gfg"
# to store files in a list
list = []
# dirs=directories
for (root, dirs, file) in os.walk(path):
for f in file:
if '.txt' in f:
print(f)
Output:

Using os.scandir() method to list files in a Directory
os.scandir() is an efficient version of os.listdir() function. It was later released by Python and is supported for Python 3.5 and greater.
Example: List all files and directories in a directory.
In this example, the Python script utilizes the os module to list files and directories in the specified path ("C://Users//Vanshi//Desktop//gfg"). It employs os.scandir() to obtain an iterator of os.DirEntry objects representing entries in the directory.
Python
# import OS module
import os
# This is my path
path = "C://Users//Vanshi//Desktop//gfg"
# Scan the directory and get
# an iterator of os.DirEntry objects
# corresponding to entries in it
# using os.scandir() method
obj = os.scandir(path)
# List all files and directories in the specified path
print("Files and Directories in '% s':" % path)
for entry in obj:
if entry.is_dir() or entry.is_file():
print(entry.name)
Output:

List Files in a Directory Using the Glob Module in Python
The glob module retrieves files/path names matching a specified pattern. Below are the ways by which we can list files in a directory using the glob module:
- glob() Method
- iglob() Method
Using the glob() method to get all files in a directory
With glob.glob, we can use wild cards ("*, ?, [ranges]) to make path retrieval more simple and convenient.
Syntax: glob.glob(pathname, *, recursive=False)
Parameters:
- pathname: The path of the directory or the pattern to match.
- recursive (Optional): A boolean parameter (default value is set to False) that indicates whether the search should be recursive, i.e., whether it should include subdirectories.
Returns:
- List of matching file paths
Example: Python file matching and printing using glob() method
Python
import glob
# This is my path
path = "C:\\Users\\Vanshi\\Desktop\\gfg"
# Using '*' pattern
print('\nNamed with wildcard *:')
for files in glob.glob(path + '*'):
print(files)
# Using '?' pattern
print('\nNamed with wildcard ?:')
for files in glob.glob(path + '?.txt'):
print(files)
# Using [0-9] pattern
print('\nNamed with wildcard ranges:')
for files in glob.glob(path + '/*[0-9].*'):
print(files)
Output:

Using iglob() method to list files in a directory
iglob() method can be used to print filenames recursively if the recursive parameter is set to True. This is used for big directories as it is more efficient than glob() method.
Syntax: glob.iglob(pathname, *, recursive=False)
Parameter:
- pathname = Path of the directory.
- recursive (Optional)= A boolean parameter (default value is set to False) that indicates whether the search should be recursive, i.e., whether it should include subdirectories.
Returns: Iterator of matching file paths
Example: Print paths matching the specified pattern in a directory.
In this example, the Python script utilizes the glob module to find and print paths matching the specified pattern ("C:\Users\Vanshi\Desktop\gfg**\*.txt"). It employs glob.iglob() to return an iterator, which is then used to print the paths of all text files present in the specified directory and its subdirectories.
Python
import glob
# This is my path
path = "C:\\Users\\Vanshi\\Desktop\\gfg**\\*.txt"
# It returns an iterator which will
# be printed simultaneously.
print("\nUsing glob.iglob()")
# Prints all types of txt files present in a Path
for file in glob.iglob(path, recursive=True):
print(file)
Output:

These are the 5 ways you can use to get details of files and directories in a directory. Python has provided multiple built-in methods that you can use to know the files present in a directory. This tutorial showed easy methods with examples to understand how to get file listings with the os module and glob module.
Similar reads:
Similar Reads
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
Python - List files in directory with extension
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 Usedos: The OS module in Python provides functions for interacting with the operating system.glob: In Python, the glob module is used to retrieve fi
3 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 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
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
List all files of certain type in a directory using Python
In python, there are several built-in modules and methods for file handling. These functions are present in different modules such as os, glob, etc. This article helps you find out many of the functions in one place which gives you a brief knowledge about how to list all the files of a certain type
3 min read
Python | os.DirEntry.is_file() method
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. os.scandir() method of os module yields os.DirEntry objects corresponding to the
3 min read
Get Current directory in Python
In this article, we will cover How to Get and Change the Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. 'GFG.txt' and if the file is not located in the directory of the script, Python raises an error. The conce
3 min read
Create a directory in Python
In Python, you can create directories to store and manage your data efficiently. This capability is particularly useful when building applications that require dynamic file handling, such as web scrapers, data processing scripts, or any application that generates output files.Let's discuss different
3 min read
Python Directory Management
Python Directory Management refers to handling and interacting with directories (folders) on a filesystem using Python. It includes creating, deleting, navigating and listing directory contents programmatically. Python provides built-in modules like os and os.path and the newer pathlib module, for t
5 min read