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

Bob*_*Bob 24 python recursion

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

kir*_*off 57

单线

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

  • @GWarner os.walk生成了多组文件(来自每个子目录).您必须总结每组的长度以获得文件的数量.如果使用len(文件),则会得到一个列表,其中每个元素都是其关联子目录中的文件数. (5认同)

Han*_*hen 21

使用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)
Run Code Online (Sandbox Code Playgroud)


Ble*_*der 6

只需添加一个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
Run Code Online (Sandbox Code Playgroud)

  • `os.path.isdir` 在 Ubuntu 上对我有用,而不是 `os.path.isfolder`。 (2认同)