Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How to List Files in a Directory with Python

Use pathlib to list a directory’s immediate entries, then filter files, match patterns, or search recursively with Python’s standard library.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s pathlib for a straightforward directory listing:

from pathlib import Path

folder = Path(".")
entries = list(folder.iterdir())
print(entries)

iterdir() returns path objects for the directory’s immediate entries, including both files and subdirectories. Choose a filter or a pattern when you need a narrower result.

As an Amazon Associate I earn from qualifying purchases.

List files and folders directly inside a directory

Path.iterdir() is a good default when you want child paths rather than just their names. The example above uses Path(".") for the current working directory; replace it with another path, such as Path("/path/to/folder"), to inspect a different location.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The entries are not returned in a guaranteed order. Sort them when the order matters, for example: entries = sorted(folder.iterdir()). If the path is not a directory or cannot be accessed, iteration raises an OSError. See the Python pathlib documentation.

Return only files or only subdirectories

Filter each child with is_file() to exclude directories:

files = [child for child in folder.iterdir() if child.is_file()]

To get immediate subdirectories instead, use is_dir():

directories = [child for child in folder.iterdir() if child.is_dir()]

These filters apply only to the directory’s immediate children; they do not search nested folders.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose an API for names, patterns, or traversal

Need API Result and behavior
Immediate child paths Path.iterdir() Yields Path objects; includes files and directories.
Immediate entry names os.listdir(path) Returns names as strings, or bytes when given a bytes path; excludes the special . and .. entries.
Matching names or extensions Path.glob(pattern) Yields matching paths, normally in one directory level unless the pattern specifies recursion.
Recursive pattern matching Path.rglob(pattern) Yields matching paths below the directory; order is not guaranteed.
Process a tree one directory at a time Path.walk() or os.walk() Provides each directory with its subdirectory names and file names. Path.walk() requires Python 3.12 or later.
Names plus entry metadata os.scandir(path) Yields DirEntry objects, useful when you also need file types or attributes.

For more detail on the os options, see the Python os documentation.

List names with os.listdir()

If strings are more convenient than path objects, use os.listdir():

import os

names = os.listdir(".")

The names are in arbitrary order. Sort them if you need consistent presentation: names = sorted(os.listdir(".")).

Match files by extension or pattern

Use glob() to select matching entries in a directory. For example, this finds Python files directly inside the current directory:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path

python_files = list(Path(".").glob("*.py"))

glob() yields paths that match the pattern, and the results are not guaranteed to be sorted. To produce stable ordering, use sorted(Path(".").glob("*.py")).

Search recursively through subdirectories

Use rglob() when matches may be nested below the starting directory:

from pathlib import Path

python_files = list(Path(".").rglob("*.py"))

rglob("*.py") is equivalent to matching with glob("**/*.py"). A recursive search can take a long time on a large directory tree. Sort the results if a predictable order is required.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Walk a directory tree level by level

When you need to process each directory separately, Path.walk() yields the current directory, subdirectory names, and non-directory names:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path

for directory, dirnames, filenames in Path(".").walk():
    for filename in filenames:
        print(directory / filename)

Path.walk() was added in Python 3.12. For older Python versions, use os.walk(). By default, Path.walk() does not follow symlinks to directories and ignores scanning errors unless you provide an on_error handler. Enabling symlink following can lead to infinite recursion if a link points to a parent directory.

Account for ordering, hidden names, and errors

  • Ordering: iterdir(), listdir(), and glob results have no guaranteed order. Sort the returned paths or names when deterministic output matters.
  • Changing directories: If entries are added or removed while a directory is being scanned or iterated, whether those changes appear in the results is unspecified.
  • Hidden names: Path.glob() and Path.rglob() normally match dot-prefixed names. The glob module instead requires a pattern beginning with a dot to match a hidden name by default; see the Python glob documentation.
  • Case sensitivity: By default, pathlib glob matching follows platform conventions, typically case-sensitive on POSIX and case-insensitive on Windows. Python 3.12 added an explicit case_sensitive option.
  • Symlinks: glob() and rglob() do not recurse through symlinks by default. Current pathlib versions provide recurse_symlinks to change that behavior; Path.walk() also defaults to not following symlink directories.
  • Glob scanning errors: In Python 3.13 and later, Path.glob() and Path.rglob() suppress OSError exceptions raised during scanning. If a program must report permission or I/O errors rather than silently skip affected directories, account for that version-specific behavior.

Use os.scandir() when metadata matters

os.scandir() returns DirEntry objects rather than plain names. The Python Software Foundation notes that using it instead of listdir() can significantly improve performance when code also needs file-type or file-attribute information, because the operating system may provide that information during the scan. The benefit depends on the filesystem and workload; no fixed timing improvement is established. Consult the os documentation for the API details.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.