Coder Perfect

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

Problem

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

I suppose the simplest method is len(glob.glob(‘*’)), however that counts the directory as a file as well.

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

Asked by prosseek

Solution #1

Using os.listdir() instead of glob.glob will be significantly more efficient. Use os.path.isfile() to see if a filename is an ordinary file (rather than a directory or other entity):

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))])

Answered by Daniel Stutzbach

Solution #2

import os

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

Answered by Luke

Solution #3

Subdirectories are included for all types of files:

import os

list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files

Only files (no subdirectories) are allowed:

import os

onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)

Answered by Guillermo Pereira

Solution #4

This is where fnmatch really shines:

import fnmatch

print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))

More details: http://docs.python.org/2/library/fnmatch.html

Answered by ngeek

Solution #5

The most pythonic way to count all files in a directory – including files in subdirectories – is to use:

import os

file_count = sum(len(files) for _, _, files in os.walk(r'C:\Dropbox'))
print(file_count)

We use sum since it is quicker than manually adding the file counts (timings pending)

Answered by Mr_and_Mrs_D

Post is based on https://stackoverflow.com/questions/2632205/how-to-count-the-number-of-files-in-a-directory-using-python