【问题标题】:Using the recursive code, I want to return a set of 2 values (total files, folders)使用递归代码,我想返回一组 2 个值(总文件、文件夹)
【发布时间】:2016-09-27 16:30:30
【问题描述】:

我编写的这个程序不使用 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 总共 700 个文件和文件夹。

我现在想做的是使用这段代码,当然还有一些修改,调用fcount('F:\\')并返回一个集合(total files, folders)

我想要的输出示例是:(700, 50)700files + folders50 只是 folders

我不知道该怎么做。

【问题讨论】:

  • 是的,使用元组。有什么问题?
  • @KarolyHorvath 不确定如何在这组代码中实现元组。

标签: python python-3.x recursion tuples subdirectory


【解决方案1】:

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

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)

【讨论】:

  • 我现在看到了。我正在将计数添加到每个循环中,并且因为我正在这样做,所以不可能为每个循环获得单独的答案。现在,我需要做的就是理解这一点。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多