How do I read the number of files in a specific folder using Python? Example code would be awesome!
To count files and directories non-recursively you can use os.listdir
and take its length.
To count files and directories recursively you can use os.walk
to iterate over the files and subdirectories in the directory.
If you only want to count files not directories you can use os.listdir
and os.path.file
to check if each entry is a file:
import os.path
path = '.'
num_files = len([f for f in os.listdir(path)
if os.path.isfile(os.path.join(path, f))])
Or alternatively using a generator:
num_files = sum(os.path.isfile(os.path.join(path, f)) for f in os.listdir(path))
Or you can use os.walk
as follows:
len(os.walk(path).next()[2])
I found some of these ideas from this thread.