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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read