pathlib.Path.iterdir()Function of the
pathlibModule to Count the Number of Files in a Directory in Python
listdir()Method of the
osModule to Count the Number of Files in a Directory in Python
In Python, whenever someone has to work with a file and perform external operations on it, the working directory is always kept in mind. Without setting the correct working directory where the required file is present, the user cannot perform any operations on that file. There might be situations when a user needs to know how many files are present in a particular directory.
This tutorial shows you methods on how to count the number of files in a directory in Python.
pathlib.Path.iterdir() Function of the
pathlib Module to Count the Number of Files in a Directory in Python
pathlib module comes under Python’s standard utility modules. This module helps the user by providing various classes and objects representing external file paths with a proper approach for interacting with operating systems.
pathlib.Path.iterdir() of the
pathlib module is used to get the path objects of the contents of a directory in Python; this is executed whenever the directory’s path is known.
import pathlib initial_count = 0 for path in pathlib.Path(".").iterdir(): if path.is_file(): initial_count += 1 print(initial_count)
In the example above, the
path.is_file() function is also used. It’s also a command of the
pathlib module used to check if the path ends on a file or not.
When used separately, this function returns a boolean value. So here, if the path leads to a file, the
initial_count increases by one.
listdir() Method of the
os Module to Count the Number of Files in a Directory in Python
os module also comes under Python’s standard utility modules. It provides various methods or functions that are very useful whenever a user interacts with the operating system.
One of the methods of the
os module is the
listdir() method. This method returns a list of all the files present in a particular directory mentioned. By default, the list of files and directories in the current working directory is returned if the user did not mention a directory.
import os initial_count = 0 dir = "RandomDirectory" for path in os.listdir(dir): if os.path.isfile(os.path.join(dir, path)): initial_count += 1 print(initial_count)
Note that in the code above, a directory is specified. Therefore, the output returned will be the number of files and directories present in that particular directory only and no other directory.
- Python Get Home Directory
- List All Files in Directory and Subdirectories in Python
- Fix the No Such File in Directory Error in Python
- Get Directory From Path in Python
- Execute a Command on Each File in a Folder in Python