Python Practice › OS Module Programs › Program 14
Count files in a folder
Write a Python program to count the files in a target path.
Output
3
Approach
- Count entries that are files.
Solution
import os os.makedirs("target/sub", exist_ok=True)for name in ["a.txt", "b.csv", "c.txt"]: open(os.path.join("target", name), "w").close()count = sum(1 for n in os.listdir("target") if os.path.isfile(os.path.join("target", n)))print(count)Output
3
Line by line
Line 6
listdir gives bare names, so each one is joined with the folder before checking.
Learn the concept
New to this topic? Read the lesson, then come back.