HOWTO · Python

How to Count the Number of Files in a Directory in Python

This tutorial demonstrates how to count the number of files in a directory in Python.

On this page

To count file entries in a specified directory, iterate over its entries and test each one with Path.is_file(). These checks follow symbolic links, so an entry is counted when its target is a file, including a symbolic link to a file. The examples below distinguish an immediate directory count from recursive traversal and pattern matching. Relative paths are resolved from Python’s current working directory, so use an absolute path or set that directory deliberately when the location matters.

Count files in one directory with pathlib

Path.iterdir() yields the entries directly inside a directory. Combine it with Path.is_file() to count entries whose targets are files, including symbolic links to files, while excluding child directories. The example creates a small directory tree; the top level contains two files and one child directory.

Run this example:

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temp_dir:
    directory = Path(temp_dir)
    (directory / "alpha.txt").write_text("A", encoding="utf-8")
    (directory / "beta.csv").write_text("B", encoding="utf-8")
    child = directory / "nested"
    child.mkdir()
    (child / "gamma.txt").write_text("C", encoding="utf-8")

    count = sum(1 for entry in directory.iterdir() if entry.is_file())
    print(f"Number of files: {count}")
Number of files: 2

The count is two because iterdir() examines only the immediate entries and is_file() filters out the nested directory. Change directory to the path you want to inspect. This is a good default when the task concerns one directory and readable path operations are useful.

Count files in one directory with os.listdir()

os.listdir(directory_path) returns the names of all immediate entries in the specified directory, including directory names. It returns entry names regardless of whether directory_path is a string or another path-like object. Join each name to the directory to form a path before checking whether that entry’s target is a file with os.path.isfile(); this also counts symbolic links to files:

sum(1 for name in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, name)))

This count is nonrecursive. If directory_path is omitted, os.listdir() lists the current working directory. Pass an explicit path when the program should not depend on where it was launched. This approach is useful when the names themselves are needed for other processing.

Count files efficiently with os.scandir()

os.scandir(directory_path) returns an iterator of os.DirEntry objects. Each entry can test its type with is_file(), which follows symbolic links by default; this counts entries whose targets are files, including symbolic links to files. A count can be written as:

sum(1 for entry in os.scandir(directory_path) if entry.is_file())

The iterator covers immediate entries, not descendants. Use with os.scandir(directory_path) as entries: when iterating explicitly so the directory iterator is closed promptly. scandir() may be a useful choice for large directories or when several entry attributes are needed; actual performance depends on the filesystem and workload, so benchmark your own case before relying on a speed difference.

Count files recursively with os.walk()

Use os.walk(directory_path) when the count should include file entries in the directory and its descendants. For each visited directory, it yields the current path, subdirectory names, and file names. The files list can include symbolic-link names whose targets are files, so adding its length counts those entries too. Add the length of each files list:

sum(len(files) for _, _, files in os.walk(directory_path))

Unlike the preceding methods, this is a tree-wide count. os.walk() reports names in its file list, which normally excludes subdirectories; if links or concurrently changing directories matter, decide how those should be treated for your application. A missing starting directory produces no yielded rows by default, so the sum is zero.

Count matching files with glob.glob()

glob.glob() selects paths using a pattern. For example, glob.glob(os.path.join(directory_path, "*.txt")) matches .txt names directly inside the specified directory. The pattern does not recurse into child directories; use a recursive pattern such as **/*.txt together with recursive=True if nested matches are wanted.

A pattern may also match a directory whose name fits it. Filter the returned paths with os.path.isfile() to count entries whose targets are files, including symbolic links to files:

sum(1 for path in glob.glob(os.path.join(directory_path, "*.txt")) if os.path.isfile(path))

Choose pathlib for a straightforward immediate count, listdir() when you need entry names, scandir() when you want entry objects, os.walk() for a whole tree, or glob.glob() when a filename pattern defines what to count.