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
One - liner
import os
cpt = sum([len(files) for r, d, files in os.walk("G:\CS\PYTHONPROJECTS")])
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)
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