You can get a list of files in a directory sorted by name using sorted(os.listdir(path)).
How to list files in a directory in Python
Key takeaways:
Use Python’s built-in modules such as
os,globorpathlibto list files in a directory depending on your needs.Use
os.listdir(path)for quick listing of files and directories, and filter withos.path.isfile()oros.path.isdir().Use
glob.glob(pattern)for pattern-based matching (e.g.,*.txt), orglob.iglob(pattern, recursive=True)to include subfolders.Use
pathlib.Path(path).iterdir()for an object-oriented approach, and filter entries withis_file()oris_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:
Using the
osmoduleUsing the
globmoduleUsing the
pathlibmodule
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
import os# Specify the directory pathdirectory = "."# List all files and directoriescontents = 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
import glob# Get all text files in the current directorytxt_files = glob.glob("*.txt")# Print the list of text filesfor 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
from pathlib import Path# Specify the directory pathdirectory = Path(".")# List all filesfiles = [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 withos.listdir().glob: Perfect for pattern-based searches (e.g., all.txtfiles).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?
What is `__file__` in Python?
How do I find files in a subfolder in Python?
How do I get a list of files in a directory in Python?
Free Resources