Python List All Files In Directory

5 min read

In Python, listing all files in a directory is a common programming task used in automation, data processing, file management, backups, testing, and many other applications. The most popular ways to do it include Python’s pathlib, os.scandir(), glob, and recursive traversal methods. This guide explains how to list files in a directory clearly and safely, including how to include hidden files, sort results, filter by extension, handle errors, and walk through subdirectories.

Introduction to Listing Files in a Directory

If you're say “list all files in a directory,” there are a few possible meanings:

  • Show only files, not folders.
  • Show every directory entry, including folders.
  • Include hidden files such as .gitignore or .bashrc.
  • Search only the current directory, or also search inside subdirectories.
  • Return file names as strings, or return full file paths.

Python gives you several built-in tools for this task. So the best choice depends on your goal. For modern Python code, pathlib is often the easiest and most readable option. For more advanced performance or control, os.scandir() is a powerful alternative It's one of those things that adds up. Surprisingly effective..

Method 1: Use pathlib.Path.iterdir()

The pathlib module is part of Python’s standard library and provides an object-oriented way to work with file paths.

List all files and folders

from pathlib import Path

directory = Path("/path/to/your/directory")

for item in directory.iterdir():
    print(item)

The iterdir() method returns all entries in the directory, including both files and subdirectories Small thing, real impact..

List only files

To list only files, use is_file():

from pathlib import Path

directory = Path("/path/to/your/directory")

for file in directory.iterdir():
    if file.is_file():
        print(file.name)

This prints only the names of files directly inside the directory. It does not include files inside subfolders.

List files with a specific extension

Take this: to list only .txt files:

from pathlib import Path

directory = Path("/path/to/your/directory")

for file in directory.Plus, iterdir():
    if file. is_file() and file.suffix == ".txt":
        print(file.

You can also use `glob()`:

```python
from pathlib import Path

directory = Path("/path/to/your/directory")

text_files = directory.glob("*.txt")

for file in text_files:
    print(file)

glob() is useful when you want to match file names using patterns.

Method 2: Use os.listdir()

The os.listdir() function is one of the simplest ways to list directory contents.

import os

directory = "/path/to/your/directory"

files = os.listdir(directory)

for file in files:
    print(file)

By default, os.listdir() returns all entries in the directory, including files and folders. It also includes hidden files on most systems, such as files beginning with a dot.

To list only files, combine os.listdir() with os.path.isfile():

import os

directory = "/path/to/your/directory"

for file in os.listdir(directory):
    full_path = os.path.join(directory, file)

    if os.path.isfile(full_path):
        print(file)

This approach is simple and widely used, but it returns file names as strings rather than Path objects Worth knowing..

Method 3: Use os.scandir()

os.scandir() is a more efficient and flexible way to list directory contents, especially when working with large directories.

import os

directory = "/path/to/your/directory"

with os.scandir(directory) as entries:
    for entry in entries:
        print(entry.name)

scandir() returns DirEntry objects, which contain useful information such as:

  • entry.name
  • entry.path
  • entry.is_dir()
  • entry.is_file()

Example:

import os

directory = "/path/to/your/directory"

with os.scandir(directory) as entries:
    for entry in entries:
        if entry.is_file():
            print(entry.

A key advantage of `scandir()` is that it can avoid unnecessary system calls when checking file types. For small scripts, this difference may not matter much, but for large directories or repeated file operations, it can improve performance.

## Difference Between Files and Directories

When listing directory contents, it is important to know the difference between files and directories.

A file might be:

```text
report.pdf
notes.txt
image.png

A directory might be:

images
documents
backup

If you want to print both, use:

from pathlib import Path

directory = Path("/path/to/your/directory")

for item in directory.iterdir():
    print(item.name)

If you want to print only files:

from pathlib import Path

directory = Path("/path/to/your/directory")

for item in directory.iterdir():
    if item.is_file():
        print(item.name)

If you want to print only directories:

from pathlib import Path

directory = Path("/path/to/your/directory")

for item in directory.iterdir():
    if item.is_dir():
        print(item.name)

Listing Files Recursively

The examples above list only files directly inside a directory. If you want to list files inside subdirectories as well, you need recursive traversal Nothing fancy..

Use pathlib.rglob()

The rglob() method recursively searches through a directory tree.

from pathlib import Path

directory = Path("/path/to/your/directory")

for file in directory.rglob("*"):
    if file.is_file():
        print(file)

This prints every file in the main directory and all nested subdirectories Small thing, real impact..

List only .py files recursively

from pathlib import Path

directory = Path("/path/to/your/directory")

python_files = directory.rglob("*.py")

for file in python_files:
    print(file)

This is useful for searching for code files, images, logs, backups, or any other file type throughout a folder structure.

Sorting Files by Name

By default, directory listing order may not be guaranteed. If you want predictable output, sort the results And that's really what it comes down to..

Sort files alphabetically

from pathlib import Path

directory = Path("/path/to/your/directory")

files = [
    file for file in directory.iterdir()
    if file.is_file()
]

for file in sorted

files):
    print(file.name)

For case-insensitive sorting:

for file in sorted(files, key=lambda item: item.name.casefold()):
    print(file.name)

This ensures names such as Zebra.txt and apple.txt are ordered consistently regardless of capitalization No workaround needed..

Sorting by Modification Time

You can also sort files according to their last modification time:

Fresh Picks

Recently Shared

You Might Like

Worth a Look

Thank you for reading about Python List All Files In Directory. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home