Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

trying to count files in a dir and subdirectories without the use of walk

I need to count the files in both the dir path I give and subdir within that path without the use of walk. This is as far as I’ve gotten:

import os

subfolder = True

path = ("C:\\Users\\user\\Documents\\Electronic Arts\\The Sims 4")
num = 0
def countFiles(path, subfolder=True):
    try:
        for entry in os.scandir(path):
            if entry.is_file():
                num += 1
            if entry.is_dir() and subfolder:
                yield countFiles(entry.path, subfolder)
        print (entry)
print (num)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import os

subfolder = True
num = 0

def countFiles(path, subfolder=True):
    global num
    for entry in os.listdir(path):
        temp_path = os.path.join(path, entry)
        if os.path.isfile(temp_path):
            num += 1
        if os.path.isdir(temp_path) and subfolder:
            countFiles(temp_path, subfolder)
    return num

num = countFiles(path)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading