scandir, a better directory iterator

1.10.0 · active · verified Sat Apr 11

scandir is a Python library that provides a faster directory iterator and a faster `os.walk()` implementation than the standard library's `os.listdir()` and `os.walk()` for older Python versions. It backported the functionality that was later added to Python 3.5 as `os.scandir`. The current version is 1.10.0, with releases occurring infrequently as new Python versions are supported or critical fixes are needed.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `scandir.scandir()` to iterate over directory entries efficiently and `scandir.walk()` for a faster directory tree traversal, similar to `os.walk()`.

import scandir
import os

def list_dir_contents(path):
    try:
        print(f"Listing contents of: {path}")
        for entry in scandir.scandir(path):
            if entry.is_file():
                print(f"  File: {entry.name}")
            elif entry.is_dir():
                print(f"  Dir: {entry.name}/")
            elif entry.is_symlink():
                print(f"  Symlink: {entry.name} -> {entry.path}")
    except FileNotFoundError:
        print(f"Error: Directory not found at {path}")
    except PermissionError:
        print(f"Error: Permission denied for {path}")

# Example usage: list current directory
list_dir_contents('.')

# Example usage: walk a directory tree
print('\nWalking directory tree:')
for root, dirs, files in scandir.walk('.'):
    level = root.count(os.sep)
    indent = ' ' * 4 * level
    print(f'{indent}{os.path.basename(root)}/')
    subindent = ' ' * 4 * (level + 1)
    for d in dirs:
        print(f'{subindent}Dir: {d}/')
    for f in files:
        print(f'{subindent}File: {f}')

view raw JSON →