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 - 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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
Understand the file system3m 26s
-
(Locked)
Navigate the file system with os module4m 55s
-
(Locked)
Use os module to uncover path and file details5m 24s
-
(Locked)
Filter path names with glob module3m 53s
-
(Locked)
Recursively list all files in a directory4m 23s
-
(Locked)
Understand Python's new pathlib module3m 42s
-
(Locked)
Create directories in Python3m 20s
-
(Locked)
Solution: Count the number of files2m 16s
-
-
-
-
-