List files with os.scandir()

EasyOS Module Programs · 31 of 49

Write a Python program to scan a folder and print all file names with os.scandir().

Advertisement
Output
['x.txt', 'y.py']

Approach

  1. scandir gives entries with name, is_file() and stat().

Solution

Python
import os os.makedirs("scan/sub", exist_ok=True)for name in ["x.txt", "y.py"]:    open(os.path.join("scan", name), "w").close()with os.scandir("scan") as entries:    print(sorted(e.name for e in entries if e.is_file()))
Output
['x.txt', 'y.py']

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Leave a Comment