Open In App

os.scandir() method

Last Updated : 20 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The os.scandir() method in Python is used to iterate over the entries (files and directories) in a specified directory. It is more efficient than older methods like os.listdir() when you need information such as file type, size or metadata, because it avoids extra system calls. We use the following folder structure in the example below:

Folder_structure
Folder structure

Example:

Python
import os

with os.scandir('.') as d:
    for e in d:
        print(e.name)

Output

example.py
example_folder
sample.txt

Explanation: os.scandir('.') returns an iterator of entries in the current directory. The with statement manages resources and the for loop prints each entry’s name.

Syntax of os.scandir()

os.scandir(path='.')

Parameters:

  • path (optional) is a string or os.PathLike object representing the path to the directory.
  • Defaults to the current directory ('.') if not specified.

Returns: An iterator of os.DirEntry objects, which contain information about the entries in the directory.

os.DirEntry Object

Attribute / Method

Description

.name

The entry's base filename (without the path).

.path

The full path to the entry.

.is_file()

Returns True if the entry is a file.

.is_dir()

Returns True if the entry is a directory.

.is_symlink()

Returns True if the entry is a symbolic link.

.stat()

Returns detailed info about the entry’s status, similar to os.stat().

Note: os.scandir() is faster than os.listdir() followed by os.stat() because each DirEntry object exposes file attributes (like .is_file() and .stat()) that are cached, reducing the number of calls to the operating system.

Examples of os.scandir()

Example 1: In this example, we check if each entry is a file using the is_file() method and list all files in the current directory.

Python
import os

with os.scandir('.') as d:
    for e in d:
        if e.is_file():
            print(e.name)

Output

example.py
sample.txt

Explanation: os.scandir('.') returns an iterator of entries in the current directory. The with statement manages resources, and the loop prints the names of entries that are files using is_file().

Example 2: In this example, we check whether each entry is a directory or a file using is_dir() and get detailed information about each entry.

Python
import os

with os.scandir('.') as ents:
    for e in ents:
        t = 'Directory' if e.is_dir() else 'File'
        s = e.stat().st_size
        print(f"{e.name} - {t} - {s} bytes")

Output

example.py - File - 193 bytes
example_folder - Directory - 0 bytes
sample.txt - File - 27 bytes

Explanation: os.scandir('.') iterate over entries in the current directory. For each entry, it checks if it’s a directory or file using is_dir(), gets its size with stat().st_size and then prints the name, type and size in bytes.

Example 3: In this example, we create a function that calls itself recursively to scan a directory’s contents.

Python
import os

def scan_dir(p):
    with os.scandir(p) as ents:
        for e in ents:
            if e.is_dir():
                print(f"Directory: {e.path}")
                scan_dir(e.path)  # Recursive call
            else:
                print(f"File: {e.path}")

scan_dir('.')

Output

File: .\example.py
Directory: .\example_folder
File: .\sample.txt

Explanation: scan_dir function scans a directory path p using os.scandir(). It prints whether each entry is a directory or file along with its full path. If an entry is a directory, the function calls itself recursively to scan that directory’s contents, enabling a full traversal of nested folders.

Handling Exception

If the directory does not exist or permissions are insufficient, os.scandir() raises exceptions like FileNotFoundError or PermissionError. You should use try-except blocks when scanning directories that may not be accessible.

Python
import os

try:
    with os.scandir('/some/protected/path') as d:
        for e in d :
            print(e.name)
except PermissionError:
    print("Permission denied!")
except FileNotFoundError:
    print("Directory not found!")

Output

Directory not found!

Explanation: This code tries to scan a directory and print its entries. If access is denied or the directory doesn’t exist, it catches the exceptions and prints an appropriate error message.


Next Article
Article Tags :
Practice Tags :

Similar Reads