Python Practice › OS Module Programs › Program 31
List files with os.scandir()
Write a Python program to scan a folder and print all file names with os.scandir().
Output
['x.txt', 'y.py']
Approach
scandirgives entries withname,is_file()andstat().
Solution
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.