The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

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

--

Chapters
00:00 Question
00:23 Accepted answer (Score 401)
00:49 Answer 2 (Score 172)
00:59 Answer 3 (Score 78)
01:23 Answer 4 (Score 51)
01:40 Thank you

--

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

Answer 3 links:
http://docs.python.org/2/library/fnmatch...

--

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