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

Estimated read time 2 min read

To count the number of files in a directory path 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 path, and then count only the files in the list.

Here’s an example:

import os

path = '/path/to/directory'
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
num_files = len(files)

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

In this example, we first specify the directory path as a string and store it in the path variable. We then use the listdir() function to get a list of all files and directories in the path, 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 files 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 path.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply