How do I count only the files in a directory? This counts the directory itself as a file:
len(glob.glob('*'))
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))])