Count files in a folder

EasyOS Module Programs · 14 of 49

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

Advertisement
Output
3

Approach

  1. Count entries that are files.

Solution

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

More os module programs

← All 49 OS Module Programs

Leave a Comment