ZetCode

Python list directory

last modified November 16, 2026 Python 3.15

In this article we show how to list directory contents in Python. Multiple examples show how to list files and directories, walk directory trees recursively, and filter the results by name, extension, size, and modification time.

A directory is an organizing unit in a computer's file system for storing and locating files. Directories are hierarchically organized into a tree; a directory can contain files and other directories. A directory is sometimes also called a folder.

Over the years, Python gained several APIs for listing directories. The object-oriented pathlib module offers Path.iterdir, Path.glob, Path.rglob, and Path.walk. The os module provides os.scandir, os.walk, and the older os.listdir. The glob and fnmatch modules match names against shell-style wildcards.

The sample directory

The examples work with a small project directory, which lies next to the scripts. It contains a hidden file, a few data files, documentation, and a source tree with a __pycache__ directory.

project
├── .gitignore
├── README.md
├── notes.txt
├── data
│   ├── archive.zip
│   ├── cities.csv
│   └── temps.csv
├── docs
│   ├── install.txt
│   └── usage.txt
└── src
    ├── main.py
    ├── utils.py
    ├── __pycache__
    │   └── utils.cpython-315.pyc
    └── tests
        └── test_utils.py

The listing functions return entries in arbitrary order, which depends on the file system. The examples sort the results so that the output is predictable.

Listing with Path.iterdir

The Path.iterdir method yields path objects for the contents of a directory. The listing is not recursive, and the special entries . and .. are not included.

iterdir_list.py
from pathlib import Path

path = Path('project')

for entry in sorted(path.iterdir()):
    print(entry)

The example lists the contents of the project directory. Both files and directories are included. Each yielded path is the directory path joined with the entry name. Path objects sort by their string value, with uppercase letters before lowercase ones.

$ python iterdir_list.py
project/.gitignore
project/README.md
project/data
project/docs
project/notes.txt
project/src

Listing only files or directories

The is_file and is_dir methods tell regular files and directories apart.

files_dirs.py
from pathlib import Path

path = Path('project')

dirs = sorted(e.name for e in path.iterdir() if e.is_dir())
files = sorted(e.name for e in path.iterdir() if e.is_file())

print('directories:', dirs)
print('files:', files)

We use generator expressions with conditions to split the entries into two lists. The name attribute is the final component of a path, without the parent directories.

$ python files_dirs.py
directories: ['data', 'docs', 'src']
files: ['.gitignore', 'README.md', 'notes.txt']

Hidden files

On Unix systems, files whose names start with a dot are hidden. Python's listing functions do not treat them specially, so we filter them by name.

hidden_files.py
from pathlib import Path

path = Path('project')

visible = sorted(e.name for e in path.iterdir() if not e.name.startswith('.'))
hidden = sorted(e.name for e in path.iterdir() if e.name.startswith('.'))

print(visible)
print(hidden)

The example separates visible and hidden entries. On Windows, hidden files are marked by a file attribute instead, which can be read from st_file_attributes of os.stat.

$ python hidden_files.py
['README.md', 'data', 'docs', 'notes.txt', 'src']
['.gitignore']

Matching names with Path.glob

The Path.glob method yields the paths that match a shell-style pattern relative to the directory. The * wildcard matches any characters within a name, ? matches one character, and [...] matches a character from a set.

globbing.py
from pathlib import Path

path = Path('project')

for e in sorted(path.glob('*.txt')):
    print(e)

print(sorted(e.name for e in path.glob('data/*.csv')))
print(sorted(e.name for e in path.glob('[!.]*')))

The first pattern finds the text files directly in project; the files in docs are not matched because the pattern has no directory part. The data/*.csv pattern looks into a subdirectory.

print(sorted(e.name for e in path.glob('[!.]*')))

Unlike the shell and the glob module, Path.glob matches hidden files with *. The [!.]* pattern excludes names that start with a dot.

$ python globbing.py
project/notes.txt
['cities.csv', 'temps.csv']
['README.md', 'data', 'docs', 'notes.txt', 'src']

Recursive listing with Path.rglob

The ** pattern component matches the directory itself and all its subdirectories, recursively. The Path.rglob method is a shortcut for Path.glob with **/ added in front of the pattern.

rglobbing.py
from pathlib import Path

path = Path('project')

for e in sorted(path.rglob('*.py')):
    print(e)

print(sorted(path.glob('**/*.py')) == sorted(path.rglob('*.py')))

The example finds all Python source files in the project tree. The last line confirms that glob('**/*.py') and rglob('*.py') return the same paths.

$ python rglobbing.py
project/src/main.py
project/src/tests/test_utils.py
project/src/utils.py
True

Filtering by multiple extensions

Glob patterns cannot express alternatives such as csv or txt. Instead, we list all files recursively and check the suffix attribute.

multiple_extensions.py
from pathlib import Path

path = Path('project')
wanted = {'.csv', '.txt', '.md'}

files = sorted(p for p in path.rglob('*') if p.is_file() and p.suffix in wanted)

for file in files:
    print(file.relative_to(path))

The suffix is the file extension including the dot. We keep the files whose suffix is in the wanted set. The relative_to method strips the project prefix from the printed paths.

$ python multiple_extensions.py
README.md
data/cities.csv
data/temps.csv
docs/install.txt
docs/usage.txt
notes.txt

Listing with os.scandir

The os.scandir function returns an iterator of os.DirEntry objects. A directory entry knows its name, path, and type, which the operating system usually reports together with the name, so calls such as is_file often need no extra system call. This makes scandir the fastest way to list large directories.

scan_dir.py
import os

with os.scandir('project/data') as it:
    entries = sorted(it, key=lambda e: e.name)

for entry in entries:
    if entry.is_file():
        print(f'{entry.name:<12} {entry.stat().st_size:>6} bytes')

The iterator is used as a context manager, which closes the underlying directory handle. We sort the entries by name and print the size of each file, obtained with the stat method of the entry.

$ python scan_dir.py
archive.zip    5200 bytes
cities.csv     1693 bytes
temps.csv       231 bytes

Recursive listing with os.scandir

Since scandir lists a single directory, a recursive listing calls it again for each subdirectory. A recursive generator does this neatly.

scan_recursive.py
import os


def scan_tree(path):
    with os.scandir(path) as it:
        for entry in it:
            if entry.is_dir(follow_symlinks=False):
                yield from scan_tree(entry.path)
            else:
                yield entry


total = 0
count = 0

for entry in scan_tree('project'):
    total += entry.stat().st_size
    count += 1

print(f'{count} files, {total} bytes')

The scan_tree generator yields file entries and delegates to itself with yield from for subdirectories. The follow_symlinks=False argument prevents endless recursion through symbolic links that point to a parent directory. We count the files and sum their sizes.

$ python scan_recursive.py
12 files, 7407 bytes

Walking a tree with os.walk

The os.walk function walks a directory tree from the top down. For each directory, it yields a three-tuple: the directory path, a list of subdirectory names, and a list of file names.

walking.py
import os

SKIP = {'__pycache__', '.git'}

for dirpath, dirnames, filenames in os.walk('project'):
    dirnames[:] = sorted(d for d in dirnames if d not in SKIP)

    print(f'{dirpath}: {sorted(filenames)}')

The example prints the files of each directory and skips the __pycache__ and .git directories.

dirnames[:] = sorted(d for d in dirnames if d not in SKIP)

In top-down mode, os.walk descends into the directories that remain in the dirnames list after our code has run. Modifying the list in place with a slice assignment prunes the walk and also sets the order of the visit.

$ python walking.py
project: ['.gitignore', 'README.md', 'notes.txt']
project/data: ['archive.zip', 'cities.csv', 'temps.csv']
project/docs: ['install.txt', 'usage.txt']
project/src: ['main.py', 'utils.py']
project/src/tests: ['test_utils.py']

Walking a tree with Path.walk

Python 3.12 added the Path.walk method, the pathlib counterpart of os.walk. It yields the directory as a Path object, so we can join file names to it with the / operator.

path_walk.py
from pathlib import Path

for root, dirs, files in Path('project').walk():
    dirs.sort()
    dirs[:] = [d for d in dirs if not d.startswith('__')]

    py_files = sorted(f for f in files if f.endswith('.py'))
    for name in py_files:
        print(root / name)

We print the full paths of all Python files. As with os.walk, we sort the dirs list and remove the directories that start with two underscores in place.

$ python path_walk.py
project/src/main.py
project/src/utils.py
project/src/tests/test_utils.py

Printing a directory tree

The following program prints the contents of a directory as a tree, similar to the tree command.

path_tree.py
from pathlib import Path


def tree(directory, prefix=''):
    entries = sorted(directory.iterdir(), key=lambda p: (p.is_file(), p.name))

    for i, path in enumerate(entries):
        last = i == len(entries) - 1
        print(f'{prefix}{"└── " if last else "├── "}{path.name}')

        if path.is_dir():
            tree(path, prefix + ('    ' if last else '│   '))


root = Path('project')
print(root.name)
tree(root)

The tree function lists one directory and calls itself for each subdirectory. The sort key (p.is_file(), p.name) puts directories before files, because False sorts before True. The last entry of a directory gets a corner connector and its children are indented with spaces instead of a vertical line.

$ python path_tree.py
project
├── data
│   ├── archive.zip
│   ├── cities.csv
│   └── temps.csv
├── docs
│   ├── install.txt
│   └── usage.txt
├── src
│   ├── __pycache__
│   │   └── utils.cpython-315.pyc
│   ├── tests
│   │   └── test_utils.py
│   ├── main.py
│   └── utils.py
├── .gitignore
├── README.md
└── notes.txt

Listing files by size

The stat method returns information about a file, including its size in bytes in the st_size attribute.

files_by_size.py
from pathlib import Path

path = Path('project')
limit = 100

files = [(p, p.stat().st_size) for p in path.rglob('*') if p.is_file()]
large = sorted((f for f in files if f[1] >= limit), key=lambda f: f[1], reverse=True)

for file, size in large:
    print(f'{size:>6}  {file}')

We collect all files with their sizes, keep those of at least 100 bytes, and sort them from the largest. In a real program, the limit would be larger, for example 1024 ** 3 for files over one gigabyte.

$ python files_by_size.py
  5200  project/data/archive.zip
  1693  project/data/cities.csv
   231  project/data/temps.csv

Listing recently modified files

The st_mtime attribute holds the time of the last modification as seconds since the epoch. Comparing it with the current time from time.time finds the files changed within a given period.

recent_files.py
import sys
import time
from datetime import datetime
from pathlib import Path

hours = float(sys.argv[1])
cutoff = time.time() - hours * 3600

for p in sorted(Path('project').rglob('*')):
    if p.is_file():
        mtime = p.stat().st_mtime
        if mtime > cutoff:
            stamp = datetime.fromtimestamp(mtime)
            print(f'{stamp:%Y-%m-%d %H:%M}  {p}')

The program takes the number of hours from the command line and prints the files modified within that period, with their modification time converted to a datetime. Before running it, we changed the modification times of a few files with the touch command.

$ python recent_files.py 1
2026-11-16 22:33  project/src/utils.py
$ python recent_files.py 24
2026-11-16 21:03  project/data/temps.csv
2026-11-16 18:03  project/notes.txt
2026-11-16 22:33  project/src/utils.py

Listing with os.listdir

The os.listdir function returns a list of the names of the entries in a directory, without the directory part and without . and ... It is the oldest API; new code usually prefers pathlib or os.scandir.

list_dir.py
import os

names = os.listdir('project')
print(sorted(names))

files = [n for n in names if os.path.isfile(os.path.join('project', n))]
print(sorted(files))

The returned names are bare names, so to test what they are we must join them with the directory path first. Forgetting this is a common bug: a bare name would be checked relative to the current working directory.

$ python list_dir.py
['.gitignore', 'README.md', 'data', 'docs', 'notes.txt', 'src']
['.gitignore', 'README.md', 'notes.txt']

Wildcards with fnmatch

The fnmatch module matches names against Unix shell-style wildcards. These are not regular expressions. The special characters are the following:

Pattern Meaning
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seq
Table: The fnmatch special characters

The fnmatch function tests one name; the filter function returns the names from a list that match a pattern.

list_fnmatch.py
import fnmatch
import os

names = sorted(os.listdir('project/docs') + os.listdir('project/data'))

print(fnmatch.filter(names, '*.csv'))
print(fnmatch.filter(names, '[a-m]*'))
print(fnmatch.filter(names, '*.???'))
print([n for n in names if fnmatch.fnmatch(n, 'u*.txt')])

We combine the names from two directories and filter them with four patterns: the CSV files, names starting with a letter from a to m, names with a three-letter extension, and text files starting with u.

$ python list_fnmatch.py
['cities.csv', 'temps.csv']
['archive.zip', 'cities.csv', 'install.txt']
['archive.zip', 'cities.csv', 'install.txt', 'temps.csv', 'usage.txt']
['usage.txt']

The glob module

The glob module returns matching paths as strings. Unlike Path.glob, it follows the shell convention and skips hidden files unless asked to include them.

glob_module.py
import glob

print(sorted(glob.glob('project/*')))
print(sorted(glob.glob('project/*', include_hidden=True)))
print(sorted(glob.glob('**/*.csv', root_dir='project', recursive=True)))

The first call lists the visible entries of project. The include_hidden=True argument, available since Python 3.11, adds the hidden ones. In the last call, root_dir sets the directory to search in, so the returned paths are relative to it, and recursive=True enables the ** pattern.

$ python glob_module.py
['project/README.md', 'project/data', 'project/docs', 'project/notes.txt', 'project/src']
['project/.gitignore', 'project/README.md', 'project/data', 'project/docs', 'project/notes.txt', 'project/src']
['data/cities.csv', 'data/temps.csv']

Directory listing as a table

The final example prints the files of the tree with their suffix, size, and modification time in aligned columns.

listing_table.py
from datetime import datetime
from pathlib import Path

path = Path('project')

print(f'{"Name":<26} {"Suffix":<7} {"Size":>6}  Modified')

for p in sorted(path.rglob('*')):
    if not p.is_file() or '__pycache__' in p.parts:
        continue
    st = p.stat()
    mtime = datetime.fromtimestamp(st.st_mtime)
    name = str(p.relative_to(path))
    print(f'{name:<26} {p.suffix or "-":<7} {st.st_size:>6}  {mtime:%Y-%m-%d %H:%M}')

F-string format specifications align the columns: <26 left-aligns a value in 26 characters and >6 right-aligns the size. The modification time is formatted with a strftime-style specification inside the f-string. Files inside __pycache__ are skipped by checking the parts of the path. Files without an extension get a dash; for pathlib, a leading dot as in .gitignore does not start a suffix.

$ python listing_table.py
Name                       Suffix    Size  Modified
.gitignore                 -           19  2026-11-14 09:30
README.md                  .md         44  2026-11-14 09:30
data/archive.zip           .zip      5200  2026-11-14 09:30
data/cities.csv            .csv      1693  2026-11-14 09:30
data/temps.csv             .csv       231  2026-11-14 09:30
docs/install.txt           .txt        26  2026-11-14 09:30
docs/usage.txt             .txt        12  2026-11-14 09:30
notes.txt                  .txt        20  2026-11-14 09:30
src/main.py                .py         49  2026-11-14 09:30
src/tests/test_utils.py    .py         74  2026-11-16 11:05
src/utils.py               .py         38  2026-11-16 11:05

Source

pathlib – Python documentation

os.scandir – Python documentation

File and directory access – Python documentation

In this article we have listed directory contents in Python. See also Python pathlib, Python os.walk, Python os.scandir, and Python glob.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.