Use os.scandir() as a context manager to ensure the iterator is
properly closed. This fixes ResourceWarning: unclosed scandir iterator
that occurs when the iterator is garbage collected without being closed.
Fixes#1972
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>