Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回目录和子目录中的文件数_Python_Recursion - Fatal编程技术网

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

Python 返回目录和子目录中的文件数,python,recursion,Python,Recursion,尝试创建一个函数,该函数返回在目录及其子目录中找到的#个文件。只需帮助入门只需添加一个负责目录的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.is

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

只需添加一个负责目录的
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

使用
os.walk
。它将为您执行递归。有关示例,请参见

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

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

@OmarSolis什么不是递归的?@OmarSolis:什么是递归?
os.path.isdir
在Ubuntu上而不是
os.path.isfolder
。你能解释一下为什么需要sum函数吗?为什么len(文件)不够?@GWarner os.walk生成了多组文件(来自每个子目录)。必须对每个集合的长度求和,才能得到文件量。如果使用len(files),则会得到一个列表,其中每个元素都是其关联子目录中的文件数。注意,您需要使用正斜杠(或\\),而不是像这里那样使用反斜杠,否则python会认为您使用的是转义符。