How to list files in a directory in Python

Key takeaways:

  • Use Python’s built-in modules such as os, glob or pathlib to list files in a directory depending on your needs.

  • Use os.listdir(path) for quick listing of files and directories, and filter with os.path.isfile() or os.path.isdir().

  • Use glob.glob(pattern) for pattern-based matching (e.g., *.txt), or glob.iglob(pattern, recursive=True) to include subfolders.

  • Use pathlib.Path(path).iterdir() for an object-oriented approach, and filter entries with is_file() or is_dir().

Listing files is a common requirement in file-handling tasks such as organizing datasets, filtering files by extensions, or simply automating repetitive directory inspections. Python offers several approaches to achieve this.

Python simplifies the task of listing files in a directory with its versatile built-in modules. Whether you're working on a file management script or analyzing directory contents, Python provides tools to get the job done efficiently. The different ways we can do that are:

  1. Using the os module

  2. Using the glob module

  3. Using the pathlib module

Different ways to list files
Different ways to list files

1. Using the os module

The os module is one of the most straightforward ways to interact with directories and file systems. We can specify the location of the directory of which we want to print the files.

Example

main.py
file3.pdf
file2.csv
file1.txt
import os
# Specify the directory path
directory = "."
# List all files and directories
contents = os.listdir(directory)
print(contents)

The directory string specifies the current folder that contains the files we want to print. The path must be relative to the location of your Python script or, if not working with files, relative to the directory where your Python shell was started.

Using the glob module

The glob module also makes it possible​ to get a list of files or folders in a directory. It allows pattern matching to list files that match specific criteria.

Example

main.py
file1.py
file2.csv
file1.txt
import glob
# Get all text files in the current directory
txt_files = glob.glob("*.txt")
# Print the list of text files
for file in txt_files:
print(file)

Filenames can also be printed recursively using the iglob method by setting the recursive parameter to True, as shown below.

for file_name in glob.iglob('Desktop/**/*.txt', recursive=True):
print(file_name)

The code searches the Desktop folder recursively and lists all .txt files. Replacing *.txt with * lists all files. The ** pattern enables recursive searching but works only when recursive is set to True.

Using the pathlib module

The pathlib module in Python provides an object-oriented approach to filesystem operations by representing files and directories as objects, rather than just strings. This allows you to interact with the filesystem using methods and properties of these objects, making the code more readable, intuitive, and less prone to errors compared to traditional string-based approaches using modules like os

Example

main.py
file3.py
file2.csv
file1.txt
from pathlib import Path
# Specify the directory path
directory = Path(".")
# List all files
files = [f for f in directory.iterdir() if f.is_file()]
print(files)

The iterdir() function iterated through all entries in the directory. We can filter results using is_file() for files or is_dir() for directories.

Learn the basics with our engaging course!

Start your coding journey with the “Learn Python” course—the perfect course for absolute beginners! Whether you’re exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun along the way. Join now and start your Python journey today—no prior experience is required!

Conclusion

Python provides multiple convenient methods for listing files in a directory, each suited to different needs:

  • os: Ideal for quick, straightforward directory listing with os.listdir().

  • glob: Perfect for pattern-based searches (e.g., all .txt files).

  • pathlib: Offers an intuitive, modern, and object-oriented interface for filesystem operations.

Whether you need simple enumeration, advanced pattern matching, or a cleaner, more Pythonic approach, these tools enable you to handle directory contents efficiently. Armed with these methods, you can streamline file organization, automate repetitive tasks, and focus on building robust, user-friendly Python applications.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to get a list of files in a directory sorted by name in Python?

You can get a list of files in a directory sorted by name using sorted(os.listdir(path)).


What is `__file__` in Python?

__file__ is a special Python variable that contains the absolute or relative path of the script being executed. It is useful for determining the script’s location, especially when working with file paths or importing modules. However, it may not be available in interactive environments like the Python shell or Jupyter Notebook.


How do I find files in a subfolder in Python?

Use os.walk() to iterate through subfolders and list files in Python.


How do I get a list of files in a directory in Python?

To get a list of files in a directory in Python, you can use the os module. The os.listdir() function retrieves all entries in the directory, and you can filter it using os.path.isfile() to include only files.


New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved