46

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

4

3 回答 3

94

一班轮

import os
cpt = sum([len(files) for r, d, files in os.walk("G:\CS\PYTHONPROJECTS")])
于 2013-06-04T06:13:25.813 回答
29

使用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)
于 2013-06-04T05:33:43.770 回答
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
于 2013-06-04T05:26:56.507 回答