How to Count the Number of Files in a Directory Using Python?

Estimated read time 2 min read

To count the number of files in a directory using Python, you can use the os module. Specifically, you can use the listdir() function to get a list of all files and directories in the specified directory, and then count only the files in the list.

Here’s an example:

import os

dir_path = '/path/to/directory'

num_files = len([f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))])

print(f'The directory {dir_path} contains {num_files} files.')

In this example, we first specify the directory path as a string and store it in the dir_path variable. We then use the listdir() function to get a list of all files and directories in the directory, and filter out only the files by checking if each item in the list is a file using the isfile() function. We use os.path.join() to join the directory path with each item in the list to form the full file path for each item.

Finally, we use the len() function to count the number of files in the resulting list and store the result in the num_files variable. We then print a message to the console indicating the number of files found in the directory.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply