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?
countfnmatchglobpython
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?
Best Answer
os.listdir()
will be slightly more efficient than usingglob.glob
. To test if a filename is an ordinary file (and not a directory or other entity), useos.path.isfile()
: