From the course: Python: Working with Files

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Solution: Count the number of files

Solution: Count the number of files - Python Tutorial

From the course: Python: Working with Files

Solution: Count the number of files

- [Instructor] Let's count the number of files in a given directory. In the sample code, we're given two helper methods, create file and create directory. These are used in the test code, so we can change how many items are in the folder. To implement this method, we'll leverage the iterdir function. We can use this on a directory path to iterate through all of the files directly in that folder. First, we'll create a path object, we'll call it dir_path. We'll also create a variable to keep track of the file count. Then we'll use a for loop to loop over all of the objects in the path, this is where iterdir comes into play. Now we only want to count the objects that are files, so we'll add an if check to make sure the file is a file and not a directory. Then if it is a file, we'll increment the count. Once we've iterated through all of the files, we can return the file count. Let's run it. Our code works as expected. Now let's try it with no files in the directory. We'll comment out our…

Contents