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

PythonCountGlobFnmatch

Python Problem Overview


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

I guess the easiest way is len(glob.glob('*')), but that also counts the directory itself as a file.

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

Python Solutions


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

Solution 2 - Python

import os

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

Solution 3 - Python

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)

Solution 4 - Python

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

Solution 5 - Python

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)

Solution 6 - Python

I am surprised that nobody mentioned os.scandir:

def count_files(dir):
    return len([1 for x in list(os.scandir(dir)) if x.is_file()])

Solution 7 - Python

Short and simple

import os
directory_path = '/home/xyz/'
No_of_files = len(os.listdir(directory_path))

Solution 8 - Python

import os
print len(os.listdir(os.getcwd()))

Solution 9 - Python

def directory(path,extension):
  list_dir = []
  list_dir = os.listdir(path)
  count = 0
  for file in list_dir:
    if file.endswith(extension): # eg: '.txt'
      count += 1
  return count

Solution 10 - Python

An answer with pathlib and without loading the whole list to memory:

from pathlib import Path

path = Path('.')

print(sum(1 for _ in path.glob('*')))  # Files and folders, not recursive
print(sum(1 for _ in path.glob('**/*')))  # Files and folders, recursive

print(sum(1 for x in path.glob('*') if x.is_file()))  # Only files, not recursive
print(sum(1 for x in path.glob('**/*') if x.is_file()))  # Only files, recursive

Solution 11 - Python

This uses os.listdir and works for any directory:

import os
directory = 'mydirpath'

number_of_files = len([item for item in os.listdir(directory) if os.path.isfile(os.path.join(directory, item))])

this can be simplified with a generator and made a little bit faster with:

import os
isfile = os.path.isfile
join = os.path.join

directory = 'mydirpath'
number_of_files = sum(1 for item in os.listdir(directory) if isfile(join(directory, item)))

Solution 12 - Python

While I agree with the answer provided by @DanielStutzbach: os.listdir() will be slightly more efficient than using glob.glob.

However, an extra precision, if you do want to count the number of specific files in folder, you want to use len(glob.glob()). For instance if you were to count all the pdfs in a folder you want to use:

pdfCounter = len(glob.glob1(myPath,"*.pdf"))

Solution 13 - Python

This is an easy solution that counts the number of files in a directory containing sub-folders. It may come in handy:

import os
from pathlib import Path

def count_files(rootdir):
    '''counts the number of files in each subfolder in a directory'''
    for path in pathlib.Path(rootdir).iterdir():
        if path.is_dir():
            print("There are " + str(len([name for name in os.listdir(path) \
            if os.path.isfile(os.path.join(path, name))])) + " files in " + \
            str(path.name))
            
 
count_files(data_dir) # data_dir is the directory you want files counted.

You should get an output similar to this (with the placeholders changed, of course):

There are {number of files} files in {name of sub-folder1}
There are {number of files} files in {name of sub-folder2}

Solution 14 - Python

def count_em(valid_path):
   x = 0
   for root, dirs, files in os.walk(valid_path):
       for f in files:
            x = x+1
print "There are", x, "files in this directory."
return x

Taked from this post

Solution 15 - Python

import os

def count_files(in_directory):
    joiner= (in_directory + os.path.sep).__add__
    return sum(
        os.path.isfile(filename)
        for filename
        in map(joiner, os.listdir(in_directory))
    )

>>> count_files("/usr/lib")
1797
>>> len(os.listdir("/usr/lib"))
2049

Solution 16 - Python

Luke's code reformat.

import os

print len(os.walk('/usr/lib').next()[2])

Solution 17 - Python

Here is a simple one-line command that I found useful:

print int(os.popen("ls | wc -l").read())

Solution 18 - Python

one liner and recursive:

def count_files(path):
    return sum([len(files) for _, _, files in os.walk(path)])

count_files('path/to/dir')

Solution 19 - Python

I used glob.iglob for a directory structure similar to

data
└───train
│   └───subfolder1
│   |   │   file111.png
│   |   │   file112.png
│   |   │   ...
│   |
│   └───subfolder2
│       │   file121.png
│       │   file122.png
│       │   ...
└───test
    │   file221.png
    │   file222.png

Both of the following options return 4 (as expected, i.e. does not count the subfolders themselves)

  • len(list(glob.iglob("data/train/*/*.png", recursive=True)))
  • sum(1 for i in glob.iglob("data/train/*/*.png"))

Solution 20 - Python

It is simple:

print(len([iq for iq in os.scandir('PATH')]))

it simply counts number of files in directory , i have used list comprehension technique to iterate through specific directory returning all files in return . "len(returned list)" returns number of files.

Solution 21 - Python

import os

total_con=os.listdir('<directory path>')

files=[]

for f_n in total_con:
   if os.path.isfile(f_n):
     files.append(f_n)


print len(files)

Solution 22 - Python

If you'll be using the standard shell of the operating system, you can get the result much faster rather than using pure pythonic way.

Example for Windows:

import os
import subprocess

def get_num_files(path):
    cmd = 'DIR \"%s\" /A-D /B /S | FIND /C /V ""' % path
    return int(subprocess.check_output(cmd, shell=True))

Solution 23 - Python

I found another answer which may be correct as accepted answer.

for root, dirs, files in os.walk(input_path):    
for name in files:
    if os.path.splitext(name)[1] == '.TXT' or os.path.splitext(name)[1] == '.txt':
        datafiles.append(os.path.join(root,name)) 


print len(files) 

Solution 24 - Python

Simpler one:

import os
number_of_files = len(os.listdir(directory))
print(number_of_files)

Solution 25 - Python

i did this and this returned the number of files in the folder(Attack_Data)...this works fine.

import os
def fcount(path):
    #Counts the number of files in a directory
    count = 0
    for f in os.listdir(path):
        if os.path.isfile(os.path.join(path, f)):
            count += 1

    return count
path = r"C:\Users\EE EKORO\Desktop\Attack_Data" #Read files in folder
print (fcount(path))

Solution 26 - Python

I solved this problem while calculating the number of files in a google drive directory through Google Colab by directing myself into the directory folder by

import os                                                                                                
%cd /content/drive/My Drive/  
print(len([x for x in os.listdir('folder_name/']))  

Normal user can try

 import os                                                                                                     
 cd Desktop/Maheep/                                                     
 print(len([x for x in os.listdir('folder_name/']))  

Solution 27 - Python

A simple utility function I wrote that makes use of os.scandir() instead of os.listdir().

import os 

def count_files_in_dir(path: str) -> int:
    file_entries = [entry for entry in os.scandir(path) if entry.is_file()]

    return len(file_entries)

The main benefit is that, the need for os.path.is_file() is eliminated and replaced with os.DirEntry instance's is_file() which also removes the need for os.path.join(DIR, file_name) as shown in other answers.

Solution 28 - Python

Convert to list after that you can Len > len(list(glob.glob('*')))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprosseekView Question on Stackoverflow
Solution 1 - PythonDaniel StutzbachView Answer on Stackoverflow
Solution 2 - PythonLukeView Answer on Stackoverflow
Solution 3 - PythonGuillermo PereiraView Answer on Stackoverflow
Solution 4 - PythonngeekView Answer on Stackoverflow
Solution 5 - PythonMr_and_Mrs_DView Answer on Stackoverflow
Solution 6 - PythonqedView Answer on Stackoverflow
Solution 7 - PythonSomyadeep ShrivastavaView Answer on Stackoverflow
Solution 8 - PythonrashView Answer on Stackoverflow
Solution 9 - PythonninjrokView Answer on Stackoverflow
Solution 10 - PythonPaulView Answer on Stackoverflow
Solution 11 - PythonjoaquinView Answer on Stackoverflow
Solution 12 - PythonLBesView Answer on Stackoverflow
Solution 13 - PythonMLDevView Answer on Stackoverflow
Solution 14 - PythonKristian DamianView Answer on Stackoverflow
Solution 15 - PythontzotView Answer on Stackoverflow
Solution 16 - PythonokobakaView Answer on Stackoverflow
Solution 17 - PythonBojan TunguzView Answer on Stackoverflow
Solution 18 - Pythonjuan IsazaView Answer on Stackoverflow
Solution 19 - Pythonuser799188View Answer on Stackoverflow
Solution 20 - PythonAgha SaadView Answer on Stackoverflow
Solution 21 - PythonMohit DabasView Answer on Stackoverflow
Solution 22 - PythonstylerView Answer on Stackoverflow
Solution 23 - PythonIsmail View Answer on Stackoverflow
Solution 24 - PythonMayur GuptaView Answer on Stackoverflow
Solution 25 - PythonSam EkoroView Answer on Stackoverflow
Solution 26 - PythonMaheepView Answer on Stackoverflow
Solution 27 - PythonKinyugoView Answer on Stackoverflow
Solution 28 - PythonEslamspotView Answer on Stackoverflow