• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Count Number of Files in Directory with Python

Count Number of Files in Directory with Python

February 16, 2022 Leave a Comment

In Python, we can count the number of files in a directory easily with the listdir() function from the Python os module.

import os

print(len(os.listdir(r"\examples")))

#Ouput:
5

Note, the listdir() function returns a list of all names in a directory. To just get all files, you can check each name with the isdir() function.

import os

path = r"\examples"

count = 0
for x in os.listdir(path):
    if !os.path.isdir(os.path.join(path,x)):
        count = count + 1

print(count)

#Output:
3

If you want just the files of a certain extension, you can use the endswith() function to check the extension of each file.

import os

path = r"\examples"

count = 0
for x in os.listdir(path):
    if x.endswith(".py"):
        count = count + 1

print(count)

#Output:
2

When working with file systems, it can be useful to be able to get the number of files in a particular directory.

The Python os module provides us with a number of great functions to be able to perform many operating system tasks.

With the os module, we can count the number of files in a particular directory easily.

The listdir() function takes in a path and gets a list of all of the files in that directory. We can then find the length of that list to get the number of files in the directory.

Below is an example of how to get the number of files in a directory using Python.

import os

print(len(os.listdir(r"/examples")))

#Ouput:
5

listdir() returns all names in a directory, so the length of listdir() will count the number of items in a directory. To just get the number of files, and ignore the subdirectories, you can check each name with the isdir() function.

import os

def countOnlyFiles(path):
    count = 0
    for x in os.listdir(path):
        if !os.path.isdir(os.path.join(path,x)):
            count = count + 1
    return count

print(countOnlyFiles(r"/examples"))

#Output:
3

To just count the number of files of a certain extension, we can loop over the files and check the extensions with the help of the endswith() function.

import os

def countPyFiles(path):
    count = 0
    for x in os.listdir(path):
        if x.endswith(".py"):
            count = count + 1
    return count

print(countPyFiles(r"/examples"))

#Output:
2

Counting the Number of Files in a Folder and All Subfolders in Python

Another great os module function is the os module walk() function. The walk() function returns the entire tree of folders and subfolders given a path.

We can use the walk() function to get all folders and subfolders, and then iterate over the returned object to count the number of files in each folder and subfolder.

Let’s say we have the following folder structure.

examples
-- code1.py
-- code2.py
-- examples1
---- code1_1.py
-- examples2
---- code2_1.py
---- code2_2.py
---- code2_3.py

In the 3 folders, we have a few files.

Let’s use the os walk() function to get the count of the files in each of the folders of our directory.

Below is the Python code which will allow you to get the number of files in each of the folders and subfolders of a given path.

import os

def getAllFiles(path):
    print(path)
    print(len(os.listdir(path)))

    for root, dirs, files in os.walk(path):
        for name in dirs:
            print(os.path.join(root,name))
            print(len(os.listdir(os.path.join(root,name))))

getAllFiles(r"\examples")

#Output:
\examples
4
\examples\examples1
1
\examples\examples2
3

From above, we know that listdir() treats all names as files. To filter out the subfolders, we can use the isdir() function.

import os

def countOnlyFiles(path):
    count = 0
    for x in os.listdir(path):
        if !os.path.isdir(os.path.join(path,x)):
            count = count + 1
    return count

def getAllFiles(path):
    print(path)
    print(countOnlyFiles(path))

    for root, dirs, files in os.walk(path):
        for name in dirs:
            print(os.path.join(root,name))
            print(countOnlyFiles(os.path.join(root,name)))

getAllFiles(r"\examples")

#Output:
\examples
2
\examples\examples1
1
\examples\examples2
3

If you want to get just files of a certain extension, then you can use the endswith() function.

import os

def countPyFiles(path):
    count = 0
    for x in os.listdir(path):
        if x.endswith(".py"):
            count = count + 1
    return count

def getAllFiles(path):
    print(path)
    print(countPyFiles(path))

    for root, dirs, files in os.walk(path):
        for name in dirs:
            print(os.path.join(root,name))
            print(countPyFiles(os.path.join(root,name)))

getAllFiles(r"\examples")

#Output:
\examples
2
\examples\examples1
1
\examples\examples2
3

Hopefully this article has been useful for you to understand how to count the number of files in a directory with Python.

Other Articles You'll Also Like:

  • 1.  Get All Substrings of a String in Python
  • 2.  Skip Numbers in Python Range
  • 3.  pandas set_value – Using at() Function to Set a Value in DataFrame
  • 4.  Factorial Program in Python Using For Loop and While Loop
  • 5.  Check if Variable is Integer in Python
  • 6.  pandas cumprod – Find Cumulative Product of Series or DataFrame
  • 7.  Convert False to 0 in Python
  • 8.  Sort Files by Date in Python
  • 9.  Python Square Root – Finding Square Roots Using math.sqrt() Function
  • 10.  Format Numbers as Dollars in Python with format()

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy