Coders Packet

Count number of Files in a Directory in Python

By B R SESHA SAI SARMA

This is the sample program used to find the number of files that are present in the given directory, written in the Python programming language.

This sample python code of snippet helps us find the number of files in a directory!

Firstly, in this code, we import os module, which provides functions for interacting with the operating system. This module also includes many functions to interact with the file system.

Then we defined the count_files() function which takes "directory" as a parameter. We also have the count variable declared. This variable is then assigned or we can say initialised with "0".

This function uses "os.walk" to recursively traverse the directory and its subdirectories. We only need the list of files (`files`), so we use `len(files)` to get the number of files in each directory and add it to the "count" variable. It increments a count variable for each file encountered during the traversal. Finally, the function returns the total count of files in the directory. 

Further, in the code, the path to the directory is provided, then the function that we used to count the files is called. Finally, using the "print" function, we print the required result, that is, the number of files in the directory.

Also, the sample directory path used in this code, that is, "path/to/your/directory" can be replaced with the actual path to our directory of interest. The code will print the number of files found in that directory.

Hence, we can easily find the number of files in a directory using the Python code!

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by B R SESHA SAI SARMA (seshasaisarma2002)

Download packets of source code on Coders Packet