Python Practice › OS Module Programs › Program 16
Count files per extension
Write a Python program to count the files of each extension in a target path.
Output
{'.csv': 1, '.py': 3, '.txt': 2}Approach
os.path.splitextplusCounter.
Solution
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.