Count the number of files in a directory in Python.
In this session, we are going to discuss how to count the total number of files in a given directory in Python.
How to Count the total number of files in a directory in Python
first os package should be installed in the system. check os is there or not in the system.
import os
if os package will not present then it will show you an error like this :
Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> import os ModuleNotFoundError: No module named 'os'
if every this is correct then write a program:
1st we have to import os package :
#import os package to use file related methods import os
Initialize the path count variable:
#initialization of file count. Number_of_files=0
Take the path of a directory, either you can manually put your directory path or you can take as an input from the user:
#path name variablle . path="C:\python3\Lib"
take a loop to travel throughout the file and increase the file count variable:
#os.walk () method is used for travel throught the fle . for files in os.walk(path): for files in path: Number_Of_Files=Number_Of_Files+1
now the whole program is :
#import os package to use file related methods import os #initialization of file count. Number_Of_Files=0 #path name variablle . path="C:\python3\Lib" #os.walk () method is used for travel throught the fle . for files in os.walk(path): for files in path: Number_Of_Files=Number_Of_Files+1 print("Total files = ",Number_Of_Files)
Output:
Total files = 67214
Read also,
Leave a Reply