HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat 2 Numbers
      • Python Example Code to Concat N Strings
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
    • Modules and Libraries
      • Python Code for Automation using BDD
      • Python Code to Load .SO File (and Invoke a Function)
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Count and List Files in a Directory

Navigating through directories and analyzing file structures is a common task in many programming projects. Python offers versatile tools through its os module to facilitate such operations.

In this article, I will show you two methods to count the number of files in a directory using Python.

  1. The first method employs a straightforward approach, iterating through the directory contents to count files directly within the specified directory.
  2. The second method extends this functionality by recursively traversing through all directories and subdirectories, providing a comprehensive count of files within the entire directory tree.

Method 1 – Using listdir() function

The code defines a function to count files in a specified directory using the `os` module, and then demonstrates how to use this function by providing a directory path.

import os

def count_files(directory):
    count = 0
    for filename in os.listdir(directory):
        if os.path.isfile(os.path.join(directory, filename)):
            count += 1
    return count

directory_path = "/path/to/your/directory"
file_count = count_files(directory_path)
print("Number of files in directory:", file_count)

Let me explain the provided Python code.

  • The code starts by importing the `os` module, which provides functions to interact with the operating system, including filesystem operations.
  • The `count_files` function takes a directory path as input and returns the count of files present in that directory.
  • Inside the `count_files` function, it iterates over the contents of the specified directory using `os.listdir(directory)`. This function returns a list of all the files and directories in the specified directory.
  • For each item in the directory, it checks whether it’s a file or not using `os.path.isfile()`. If it’s a file, it increments the count.
  • After iterating through all items in the directory, the function returns the final count of files.
  • The code outside the function assigns the directory path to a variable `directory_path` and then calls the `count_files` function with this path. It prints the result, which is the number of files in the specified directory.
  • Before running the code, you need to replace `”/path/to/your/directory”` with the actual path to the directory you want to count the files in.

Method 2 – Using walk() function

This method extends the previous functionality to count files not only in the specified directory but also in all of its subdirectories recursively, providing a comprehensive count of files in the entire directory tree.

import os

def count_files_recursive(directory):
    count = 0
    for root, dirs, files in os.walk(directory):
        count += len(files)
    return count

directory_path = "/path/to/your/directory"
file_count_recursive = count_files_recursive(directory_path)
print("Number of files in directory and subdirectories:", file_count_recursive)

Let me walk through the above written code.

  • The code imports the `os` module for interacting with the operating system.
  • This new function, `count_files_recursive`, takes a directory path as input and returns the count of files present in that directory and all its subdirectories.
  • Inside the `count_files_recursive` function, it utilizes `os.walk(directory)`. This function generates the file names in a directory tree by walking either top-down or bottom-up through the directory tree. Here, it’s used for a top-down traversal.
  • For each directory visited (including the starting directory and its subdirectories), it provides a tuple containing the directory path (`root`), a list of subdirectories (`dirs`), and a list of files (`files`).
  • In each iteration, it increments the count by the length of the `files` list, which represents the number of files in the current directory.
  • After traversing all directories and subdirectories, the function returns the final count of files found.
  • Outside the function, the code assigns the directory path to `directory_path`, calls the `count_files_recursive` function with this path, and prints out the result, which is the total number of files in the specified directory and its subdirectories.

Both the methods are simple ways to find the number of files in a directory.

List files in a directory

Similarly, you can also list the files in a specific directory using the below code. It prints the list of files in the given directory.

import os

def list_files(directory):
    files = []
    for filename in os.listdir(directory):
        if os.path.isfile(os.path.join(directory, filename)):
            files.append(filename)
    return files

directory_path = "/path/to/your/directory"
file_list = list_files(directory_path)
print("Files in directory:")
for file_name in file_list:
    print(file_name)

 

This Python code utilizes the os module to list all files within a specified folder. Inside the list_files function, it iterates through the folder contents using os.listdir(directory) and checks if each item is a file using os.path.isfile(). If a file is found, its name is appended to a list. It also prints out the list of file names.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Code to Clear Contents of a File
Up Next
Modules and Libraries
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2026 Happiom. All Rights Reserved.