Python Practice › OS Module Programs › Program 15
Count folders in a folder
Write a Python program to count the folders in a target path.
Output
3
Approach
os.scandirgives entries withis_dir().
Solution
import os for d in ["one", "two", "three"]: os.makedirs(os.path.join("target", d), exist_ok=True)open(os.path.join("target", "file.txt"), "w").close()with os.scandir("target") as entries: print(sum(1 for e in entries if e.is_dir()))Output
3
Learn the concept
New to this topic? Read the lesson, then come back.