How do I list all files in a directory in Python?

Sometimes, when working with files in Python, there is an issue with how to get all files in a directory. In this article, we will discuss different methods on how to list all file names in a directory in Python.

Table of Contents:

What is a Directory in Python?

A directory in Python can be referred to as a location where you can store files and other directories. It is like a folder where you can store and organize your files, such as your images, videos, and documents. Python also gives you various built-in modules such as os or glob for it to interact with the directories and the files. These are some of the modules that allow you to perform tasks like listing, creating, deleting, or moving files and directories smoothly.

Master Python Programming
Learn the World's Most Versatile Language – From Basics to Advanced Applications!
quiz-icon

How to List Files in a Directory in Python

There are various methods to list all the files within a directory. Here you can use modules such as OS and glob based on your requirements. In this blog, let us discuss the modules and their purpose, which is used to extract the list of files in a directory. 

List Files in a Directory Using OS Module in Python

The os module in Python gives you tools to interact with the operating system, including listing your files in a directory. Now let us understand the methods available with the OS module:

1. Get the list of files using os.listdir() method

The os.listdr() method returns a list of all the files and the directories in a fixed path.

The os.listdir() function only retrieves files and folders from the first-level directory and does not include items from other subdirectories.

Example 1: Get a list of all files in a directory

import os

# You need to specify the directory path

test_directory = "C:/testdirectory"

# If you want to get all files and folders

test_items = os.listdir(test_directory)

print("All items in the directory:", test_items)

Output:

If the directory contains file1.txt, file2.png, and a folder named Folder1, it will print:

All items in the directory: [‘file1.txt’, ‘file2.png’, ‘Folder1’]

Example 2: Get all the files and no folders

import os

test_directory = "C:/test_directory"

# When you want to list only files (exclude folders)

test_files = [f for f in os.listdir(test_directory) if os.path.isfile(os.path.join(test_directory, f))]

print("Files only:", test_files)

Output:

Files only: [‘file1.txt’, ‘file2.png’]

Example 3: Get only ‘.txt’ files from the directory

import os

test_directory = "C:/test_directory"

# List only .txt files

test_files = [f for f in os.listdir(test_directory) if f.endswith(".txt")]

print("Text files:", test_files)

Access files in a Directory tree using os.walk() method

The os.walk() method lets you navigate through a directory and its subdirectories.

Example: Get only ‘.txt’ files in a directory

import os

test_directory = "C:/test_directory"

# Walk through the directory tree

for root, dirs, files in os.walk(test_directory):

    for testfile in files:

        if file.endswith(".txt"):

            print("Text file found:", os.path.join(root, testfile))

Output:

Text file found: C:/test_directory/testfile1.txt
Text file found: C:/test_directory/testfolder1/testfile2.txt

2. Using os.scandir() method to list files in a Directory

The os.scandir() method gives you an efficient way to list down all the files and directories. It returns you an iterator of DirEntry objects, which include the details of the file and directory.

import os

test_directory = "C:/test_directory"

# Use os.scandir to list files

with os.scandir(test_directory) as entries:

    for entry in entries:

        if entry.is_file():

            print("File:", entry.name)

Output:

File: testfile1.txt
File: testfile2.png

Python: Your Gateway to Success!
Enroll in our Course and Beging your journey now.
quiz-icon

List Files in a Directory Using the Glob Module in Python

The glob module is being used to find the files that match a particular pattern. It is especially useful when you need to search for files with specific extensions or names.

1. Using the glob() method to get all files in a directory

import glob

# Specify the directory path

test_directory = "C:/test_directory/*"

# Get all files and folders

test_items = glob.glob(test_directory)

print("All items:", test_items)

Output:

All items: [‘C:/test_directory/testfile1.txt’, ‘C:/test_directory/testfile2.png’]

2. Using iglob() method to list files in a directory 

The iglob() method works just like glob but is more memory efficient for large directories because it returns an iterator instead of a list.

Example: Print paths matching the specified pattern in a directory.

import glob

# Specify the directory path and file pattern

test_directory = "C:/test_directory/*.txt"

# Use iglob to match files

for testfile in glob.iglob(test_directory):

    print("Text file:", testfile)

Output:

Text file: C:/test_directory/testfile1.txt

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

Python gives you various ways to list your files in a directory, which extends from basic methods such as os.listdir() to advanced methods like os.walk(). By mastering these methods, you can easily manage all your files and directories in Python, depending on whether you are organizing your photos or automating any tasks.  If you want to learn more about it, you can enroll in Intellipaat’s Python Certification Course and give your career the right rift.

About the Author

Principal Data Scientist

Meet Akash, a Principal Data Scientist with expertise in advanced analytics, machine learning, and AI-driven solutions. With a master’s degree from IIT Kanpur, Aakash combines technical knowledge with industry insights to deliver impactful, scalable models for complex business challenges.

EPGC Data Science Artificial Intelligence