How to Count the Number of Files and Directory in Python

Last updated on by Digamber

This tutorial helps you learn how to quickly and easily count the number of files and the total number of directories on specific PATH recursively in a python application.

Use OS Module

In order to count files and directory, we are taking the help of the Python OS pre-defined module, and it counts files and total number directories on a given PATH pretty quickly.

import os

Set Root Folder PATH

First, define the APP_FOLDER variable with the path indicated towards the project.

We have also created the two variables; the first one is counting the total files number and the other for calculating the total directories.

APP_FOLDER = 'C:/Positronx/Python/Scripts/'

totalFiles = 0
totalDir = 0

Incorporate Walk Function with OS Module

The walk() method takes the Root folder path as a parameter, and it will display the name of the directory and files.

It scans through file and directory names in an either upwards or downwards tree format. It generates three tuple, which includes dirnames, filenames, and dirpath.

for base, dirs, files in os.walk(APP_FOLDER):
    print('Searching in : ',base)
    for directories in dirs:
        totalDir += 1
    for Files in files:
        totalFiles += 1

Its time to print the enumerate files and directories of a Python app, so print the count as intact, so use the following code to get the counting.

print('Total number of files',totalFiles)
print('Total Number of directories',totalDir)
print('Total:',(totalDir + totalFiles))

Eventually, we have completed this tutorial, and i hope this tutorial will help you understand how to count the number of files and folders in python.

Here is the final code that you can use to get the task done.

import os

APP_FOLDER = 'C:/Positronx/Python/Scripts/'

totalFiles = 0
totalDir = 0

for base, dirs, files in os.walk(APP_FOLDER):
    print('Searching in : ',base)
    for directories in dirs:
        totalDir += 1
    for Files in files:
        totalFiles += 1


print('Total number of files',totalFiles)
print('Total Number of directories',totalDir)
print('Total:',(totalDir + totalFiles))