Python os.scandir() Method

Python os.scandir() method is used to scan the directory and yield os.DirEntry objects include file attribute information and can perform common path operations.

This method is more efficient than the os.listdir() function for large directories, as it retrieves file attributes along with the file names.

Syntax

os.scandir(path='.')

Parameters

Name Description
path (optional) The path to the directory you want to scan. The default is the current directory, denoted by ‘.’.

Return value

It returns an iterator of os.DirEntry objects for entries in the directory.

Example 1: Basic usage

Our current working directory looks like this:

Screenshot of current working directory

import os

# Using scandir to list directory contents
with os.scandir('/Users/krunallathiya/Desktop/Code/pythonenv/env') as entries:
  for entry in entries:
    print(entry.name)

Output

Output of scandir() method in Python

Remember to use the (with statement) along with os.scandir() method to ensure that resources are correctly released after processing the directory entries.

Example 2: Checking if the entry is a file or directory

import os

with os.scandir('/Users/krunallathiya/Desktop/Code/pythonenv/env') as entries:
  for entry in entries:
    if entry.is_file():
      print(f"{entry.name} is a file")
    elif entry.is_dir():
      print(f"{entry.name} is a directory")

Output

Output of Checking if the entry is a file or directory

Example 3: Getting More Attributes

import os

with os.scandir('/Users/krunallathiya/Desktop/Code/pythonenv/env') as entries:
  for entry in entries:
    info = entry.stat()
    print(f"{entry.name}: Last modified: {info.st_mtime}")

Output

Output of getting more attributes using os.scandir()

Example 4: Handling errors

import os

try:
  with os.scandir('nonexistent_directory') as entries:
  for entry in entries:
    print(entry.name)
except FileNotFoundError as error:
  print(f"Error: {error}")

Output

Error: [Errno 2] No such file or directory: 'nonexistent_directory'

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.