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 :
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)