0
0
PythonHow-ToBeginner · 3 min read

How to Count Files in a Directory Using Python

You can count files in a directory in Python using the os or pathlib modules. For example, use len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]) to count files only, excluding folders.
📐

Syntax

To count files in a directory, you typically list all items in the directory and then filter only the files. Here are two common ways:

  • Using os module: os.listdir(path) lists all items, and os.path.isfile() checks if an item is a file.
  • Using pathlib module: Path(path).iterdir() lists items, and is_file() checks if it is a file.
python
import os

path = "."  # current directory

# Count files in directory
files_count = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
💻

Example

This example shows how to count only files in the current directory using both os and pathlib. It prints the number of files found.

python
import os
from pathlib import Path

path = "."  # current directory

# Using os module
files_os = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
print(f"Number of files using os: {len(files_os)}")

# Using pathlib module
p = Path(path)
files_pathlib = [f for f in p.iterdir() if f.is_file()]
print(f"Number of files using pathlib: {len(files_pathlib)}")
Output
Number of files using os: 5 Number of files using pathlib: 5
⚠️

Common Pitfalls

Some common mistakes when counting files:

  • Counting directories as files by not filtering with isfile().
  • Using os.listdir() without joining the path, which can cause errors if the script runs from a different folder.
  • Not handling hidden files or symbolic links if needed.
python
import os

path = "."

# Wrong: counts directories too
all_items = os.listdir(path)
print(f"Count including folders: {len(all_items)}")

# Right: count files only
files_only = [f for f in all_items if os.path.isfile(os.path.join(path, f))]
print(f"Count files only: {len(files_only)}")
Output
Count including folders: 8 Count files only: 5
📊

Quick Reference

Summary tips for counting files in a directory:

  • Use os.listdir() or Path.iterdir() to list directory contents.
  • Filter with os.path.isfile() or Path.is_file() to count files only.
  • Always join paths correctly with os.path.join() or use Path objects.
  • Consider hidden files or symbolic links if your use case requires it.

Key Takeaways

Use os.listdir() with os.path.isfile() or pathlib.Path.iterdir() with is_file() to count files.
Always join directory path and filename to avoid errors when checking file types.
Filtering out directories is essential to count only files.
Both os and pathlib modules are effective; pathlib offers a modern, object-oriented approach.
Watch out for hidden files or symbolic links depending on your needs.