Python 使用递归代码,我想返回一组2个值(文件总数、文件夹总数)

Python 使用递归代码,我想返回一组2个值(文件总数、文件夹总数),python,python-3.x,recursion,tuples,subdirectory,Python,Python 3.x,Recursion,Tuples,Subdirectory,我编写的这个程序不使用os.walk()、glob或fnmatch,这是有意的。它查看目录以及指定目录中的所有子目录和文件,并返回其中有多少文件+文件夹 import os def fcount(path): count = 0 '''Folders''' for f in os.listdir(path): file = os.path.join(path, f) if os.path.isdir(file):

我编写的这个程序不使用os.walk()、glob或fnmatch,这是有意的。它查看目录以及指定目录中的所有子目录和文件,并返回其中有多少文件+文件夹

import os

def fcount(path):
    count = 0

    '''Folders'''
    for f in os.listdir(path):
        file = os.path.join(path, f)
        if os.path.isdir(file):
            file_count = fcount(file)
            count += file_count + 1

    '''Files'''
    for f in os.listdir(path):
        if os.path.isfile(os.path.join(path, f)):
            count += 1
    return count

path = 'F:\\'
print(fcount(path))
我得到的一个示例输出是目录F给了我700个文件和文件夹

我现在想做的是使用这段代码,当然还有一些修改,调用
fcount('F:\\')
,并返回一组
(总文件、文件夹)

我想要的一个输出示例是:
(700,50)
700
文件+文件夹
50
只是
文件夹


我不知道怎么做。

保留两个计数并将它们作为元组返回:

total_count = dir_count = 0, 0
# .. increment either as needed
return total_count, dir_count
您只需要循环一次
os.listdir()
;您已经检测到某个内容是文件还是目录,因此只需在该内容的一个循环中进行区分:

def fcount(path):
    total_count = dir_count = 0

    for f in os.listdir(path):
        file = os.path.join(path, f)
        if os.path.isdir(file):
            recursive_total_count, recursive_dir_count = fcount(file)
            # count this directory in the total and the directory count too
            total_count += 1 + recursive_total_count
            dir_count += 1 + recursive_dir_count
        elif if os.path.isfile(file):
            total_count += 1
    return file_count, total_count

path = 'F:\\'
print(fcount(path))
最后的
print()
然后打印一个包含计数的元组;您始终可以将其拆分为:

total_count, dir_count = fcount(path)
print('Total:', total_count)
print('Directories:', dir_count)

保留两个计数并将其作为元组返回:

total_count = dir_count = 0, 0
# .. increment either as needed
return total_count, dir_count
您只需要循环一次
os.listdir()
;您已经检测到某个内容是文件还是目录,因此只需在该内容的一个循环中进行区分:

def fcount(path):
    total_count = dir_count = 0

    for f in os.listdir(path):
        file = os.path.join(path, f)
        if os.path.isdir(file):
            recursive_total_count, recursive_dir_count = fcount(file)
            # count this directory in the total and the directory count too
            total_count += 1 + recursive_total_count
            dir_count += 1 + recursive_dir_count
        elif if os.path.isfile(file):
            total_count += 1
    return file_count, total_count

path = 'F:\\'
print(fcount(path))
最后的
print()
然后打印一个包含计数的元组;您始终可以将其拆分为:

total_count, dir_count = fcount(path)
print('Total:', total_count)
print('Directories:', dir_count)

是的,使用元组。有什么问题?@KarolyHorvath不确定如何在这组代码中实现元组。是的,使用元组。有什么问题?@KarolyHorvath不知道如何在这组代码中实现元组。我现在看到了。我将计数添加到每个循环中,因为我这样做了,所以不可能为每个循环获得单独的答案。现在,我需要做的就是明白这一点。非常感谢。我现在看到了。我将计数添加到每个循环中,因为我这样做了,所以不可能为每个循环获得单独的答案。现在,我需要做的就是明白这一点。非常感谢。