I am trying to count all the files in a folder and all its subfolders For exemple, if my folder looks like this:
file1.txt
subfolder1/
├── file2.txt
├── subfolder2/
│ ├── file3.txt
│ ├── file4.txt
│ └── subfolder3/
│ └── file5.txt
└── file6.txt
file7.txt
I would like get the number 7.
The first thing I tried is a recursive function who count all files and calls itself for each folder
def get_file_count(directory: str) -> int:
count = 0
for filename in os.listdir(directory):
file = (os.path.join(directory, filename))
if os.path.isfile(file):
count += 1
elif os.path.isdir(file):
count += get_file_count(file)
return count
This way works but takes a lot of time for big directories.
I also remembered this post, which shows a quick way to count the total size of a folder using win32com and I wondered if this librairy also offered a way to do what I was looking for. But after searching, I only found this
fso = com.Dispatch("Scripting.FileSystemObject")
folder = fso.GetFolder(".")
size = folder.Files.Count
But this only returns the number of files in only the targeted folder (and not in its subfolders)
So, do you know if there is an optimal function in python that returns the number of files in a folder and all its subfolders?
IIUC, you can just do
sum(len(files) for _, _, files in os.walk('path/to/folder'))
or perhaps, to avoid the len
for probably slightly better performance:
sum(1 for _, _, files in os.walk('folder_test') for f in files)