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

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


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 CWDprint len([name for name in os.listdir('.') if os.path.isfile(name)])# path joining version for other pathsDIR = '/tmp'print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])


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


For all kind of files, subdirectories included:

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

Only files (avoiding subdirectories):

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