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

ID : 10209

viewed : 43

Tags : pythoncountglobfnmatchpython

Top 5 Answer for How to count the number of files in a directory using Python

vote vote

99

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

90

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

74

For all kind of files, subdirectories included:

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

Only files (avoiding subdirectories):

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

60

This is where fnmatch comes very handy:

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

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

vote vote

50

If you want to count all files in the directory - including files in subdirectories, the most pythonic way is:

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

We use sum that is faster than explicitly adding the file counts (timings pending)

Top 3 video Explaining How to count the number of files in a directory using Python

Related QUESTION?