The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Isolated

--

Chapters
00:00 How To Count The Number Of Files In A Directory Using Python
00:17 Accepted Answer Score 427
00:40 Answer 2 Score 186
00:47 Answer 3 Score 53
00:59 Answer 4 Score 86
01:16 Thank you

--

Full question
https://stackoverflow.com/questions/2632...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #count #glob #fnmatch

#avk47



ACCEPTED ANSWER

Score 427


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



ANSWER 2

Score 186


import os

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



ANSWER 3

Score 86


For all kind of files, subdirectories included (Python 2):

import os

lst = os.listdir(directory) # your directory path
number_files = len(lst)
print number_files

Only files (avoiding subdirectories):

import os

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



ANSWER 4

Score 53


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