Count files per extension

EasyOS Module Programs · 16 of 49

Write a Python program to count the files of each extension in a target path.

Advertisement
Output
{'.csv': 1, '.py': 3, '.txt': 2}

Approach

  1. os.path.splitext plus Counter.

Solution

Python
import osfrom collections import Counter os.makedirs("target", exist_ok=True)for name in ["a.txt", "b.txt", "c.csv", "d.py", "e.py", "f.py"]:    open(os.path.join("target", name), "w").close()counts = Counter(os.path.splitext(n)[1] for n in os.listdir("target"))print(dict(sorted(counts.items())))
Output
{'.csv': 1, '.py': 3, '.txt': 2}

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