Python 返回目录和子目录中的文件数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16910330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:58:55  来源:igfitidea点击:

Return number of files in directory and subdirectory

pythonrecursion

提问by Bob

Trying to create a function that returns the # of files found a directory and its subdirectories. Just need help getting started

尝试创建一个函数,该函数返回找到的目录及其子目录的文件数。只是需要帮助入门

回答by Blender

Just add an elifstatement that takes care of the directories:

只需添加一个elif处理目录的语句:

def fileCount(folder):
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir(folder):
        path = os.path.join(folder, filename)

        if os.path.isfile(path):
            count += 1
        elif os.path.isfolder(path):
            count += fileCount(path)

    return count

回答by Hans Then

Use os.walk. It will do the recursion for you. See http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/for an example.

使用os.walk. 它会为你做递归。有关示例,请参见http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/

total = 0
for root, dirs, files in os.walk(folder):
    total += len(files)

回答by kiriloff

One - liner

一字型

import os
cpt = sum([len(files) for r, d, files in os.walk("G:\CS\PYTHONPROJECTS")])