Count folders in a folder

EasyOS Module Programs · 15 of 49

Write a Python program to count the folders in a target path.

Advertisement
Output
3

Approach

  1. os.scandir gives entries with is_dir().

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment