How to count the number of files in a directory using Python


Question

I need to count the number of files in a directory using Python.

I guess the easiest way is len(glob.glob('*')), but that also counts the directory itself as a file.

Is there any way to count only the files in a directory?

1
177
3/20/2019 12:43:00 AM

Accepted Answer

os.listdir() will be slightly more efficient than using glob.glob. To test if a filename is an ordinary file (and not a directory or other entity), use os.path.isfile():

import os, os.path

# simple version for working with CWD
print len([name for name in os.listdir('.') if os.path.isfile(name)])

# path joining version for other paths
DIR = '/tmp'
print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
221
9/15/2014 10:06:40 PM

import os

path, dirs, files = next(os.walk("/usr/lib"))
file_count = len(files)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon