我需要在不使用walk的情况下计算我给出的dir路径和该路径内的子目录中的文件数量。这是我目前为止看到的:
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)
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)
您可以使用os.scandir
对于Python 3.4或更早版本,使用os.listdir