In this article, we will see how to count the number of files present in a directory in Python.
If the directory contains many files and you want to count the number of files present in a directory before performing any operations. For example, you want to move all files from one directory to another. Still, before moving them, we can count how many files are present in a directory to understand its impact and the time required to perform that operation.
There are multiple ways to count files of a directory. We will use the following four methods.
Table of contents
How to count Files in a directory
Getting a count of files of a directory is easy as pie! Use the
isfile() functions of an os module to count the number of files of a directory. Here are the steps.
- Import os module
The os module provides many functions for interacting with the operating system. Using the os module, we can perform many file-related operations such as moving, copying, renaming, and deleting files.
- create a counter variable
Set counter to zero. This counter variable contains how many files are present in a directory.
- Use os.listdir() function
os.listdir('path')function returns a list of files and directories present in the given directory.
- Iterate the result
Use for loop to Iterate the entries returned by the
listdir()function. Using for loop we will iterate each entry returned by the
- Use isfile() function and increment counter by 1
In each loop iteration, use the
os.path.isfile('path')function to check whether the current entry is a file or directory. If it is a file, increment the counter by 1.
Example: Count Number Files in a directory
The ‘account’ folder present on my system has three files. Let’s see how to print the count of files.
import os # folder path dir_path = r'E:\account' count = 0 # Iterate directory for path in os.listdir(dir_path): # check if current path is a file if os.path.isfile(os.path.join(dir_path, path)): count += 1 print('File count:', count)
File count: 3
A compact version of the above code using a list comprehension.
import os dir_path = r'E:\demos\files_demos\account' print(len([entry for entry in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, entry))]))
Count all files in the directory and its subdirectories
Sometimes we need to count files present in subdirectories too. In such cases, we need to use the recursive function to iterate each directory recursively to count files present in it until no further sub-directories are available from the specified directory.
The os.walk() Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at the directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
For example, calling the
os.walk('path') will yield two lists for each directory it visits. The first list contains files, and the second list includes directories.
Let’s see how to use the
os.walk() to count files present in a directory and its subdirectories.
The ‘account’ folder on my system contains three files and one subdirectory containing one file. so we must get a 4 as the final count.
import os count = 0 for root_dir, cur_dir, files in os.walk(r'E:\account'): count += len(files) print('file count:', count)
file count: 4
scandir() to count all files in the directory
scandir() function of an os module returns an iterator of os.DirEntry objects corresponding to the entries in the directory.
- Use the
os.scadir()function to get the names of both directories and files present in a given directory.
- Next, iterate the result returned by the scandir() function using a for loop
- Next, In each iteration of a loop, use the
isfile()function to check if it is a file or directory. if yes increment the counter by 1
Note: If you need file attribute information along with the count, using the
scandir() instead of
listdir() can significantly increase code performance because
os.DirEntry objects expose this information if the operating system provides it when scanning a directory.
import os count = 0 dir_path = r'E:\account' for path in os.scandir(dir_path): if path.is_file(): count += 1 print('file count:', count)
file count: 3
fnmatch module to count all files in the directory
The fnmatch supports pattern matching, and it is faster.
- For example, we can use fnmatch to find files that match the pattern
*is a wildcard which means any name. So
*.*indicates any file name with any extension, nothing but all files.
- Next, we will use the
filter()method to separate files returned by the
listdir()function using the above pattern
- In the end, we will count files using the
import fnmatch dir_path = r'E:\demos\files_demos\account' count = len(fnmatch.filter(os.listdir(dir_path), '*.*')) print('File Count:', count)
File Count: 3