Skip to content Skip to sidebar Skip to footer

Return Number Of Files In Directory And Subdirectory

Trying to create a function that returns the # of files found a directory and its subdirectories. Just need help getting started

Solution 1:

One - liner

import os
cpt = sum([len(files) for r, d, files in os.walk("G:\CS\PYTHONPROJECTS")])

Solution 2:

Use os.walk. It will do the recursion for you. See http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/ for an example.

total = 0
for root, dirs, files in os.walk(folder):
    total += len(files)

Solution 3:

Just add an elif statement that takes care of the directories:

def fileCount(folder):
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir(folder):
        path = os.path.join(folder, filename)

        if os.path.isfile(path):
            count += 1
        elif os.path.isfolder(path):
            count += fileCount(path)

    return count

Post a Comment for "Return Number Of Files In Directory And Subdirectory"