Count Number of Files in Directory Python

Count Number Of Files In Directory Python | In Python, whenever someone has to work with a file and execute outer functions, the working directory is always preserved in the sense. Without specifying the proper working directory where the file is present, the user cannot execute any operations on that file. There might be circumstances when a user needs to know how many files are in a particular directory.

In the article, we will learn, how to count the number of files in a folder using Python programming language.

Count Number Of Files In Directory Python Using pathlib.Path.iterdir() Function

We can use pathlib.Path.iterdir() function of the pathlib module to count the number of files in a directory in Python.

The pathlib module comes under Python’s standard utility modules. It helps by providing various classes and objects representing external file paths. The pathlib.Path.iterdir() of the pathlib module is used to get the path objects of the contents of a directory in Python.

import pathlib
initial_count = 0
for path in pathlib.Path(".").iterdir():
    if path.is_file():
        initial_count += 1

print(initial_count)

In the Path() we have passed “.” which represents the current working directory where the python file having the above code is located. In the above example, the path.is_file() function used. So here, if the path leads to a file, the initial_count increases by one.

Count Number Of Files In Directory Python Using listdir() Function

We can also use the listdir() method of the os module to count the number of files in a directory in Python. The listdir() method returns a list of all the files present in a particular directory.

import os
initial_count = 0
dir = "." # pass directory
for path in os.listdir(dir):
    if os.path.isfile(os.path.join(dir, path)):
        initial_count += 1
print(initial_count)

In the above example, the current working directory is specified. So, the output returned will be the number of files present in that particular directory.

So here, we have discussed how to count the number of files in a directory in Python programming language. Hope you all find this article useful.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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