I need to count the number of files in a directory using Python. I guess the easiest way is len(glob.glob('*')), but I also count the directory as file.
Is there any way to count only the files in a directory?
I need to count the number of files in a directory using Python. I guess the easiest way is len(glob.glob('*')), but I also count the directory as file.
Is there any way to count only the files in a directory?
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
print len([name for name in os.listdir('.') if os.path.isfile(name)])
import os
number_of_files = len([item for item in os.listdir(directory) if os.path.isfile(item)])
joaquin
def count_em(valid_path):
x = 0
for root, dirs, files in os.walk(valid_path):
for f in files:
x = x+1
print "There are", x, "files in this directory."
return x
Taked from this post
import os
def count_files(in_directory):
joiner= (in_directory + os.path.sep).__add__
return sum(
os.path.isfile(filename)
for filename
in map(joiner, os.listdir(in_directory))
)
>>> count_files("/usr/lib")
1797
>>> len(os.listdir("/usr/lib"))
2049