如何获取包含子目录的目录中的特定文件总数?

时间:2016-12-14 10:50:31

标签: python

以下python代码计算我在包含多个子目录的目录中的总文件数。结果将打印子目录名称及其包含的文件数。

如何修改它以便:

  • 它只查找特定的文件扩展名(即" * .shp")
  • 它提供" .shp"的数量。每个子目录中的文件以及所有" .shp"的最终计数文件

以下是代码:

import os
path = 'path/to/directory'
folders = ([name for name in os.listdir(path)])
for folder in folders:
    contents = os.listdir(os.path.join(path,folder))
    print(folder,len(contents))

2 个答案:

答案 0 :(得分:1)

你可以在字符串上使用.endswith()函数。这对于识别扩展非常方便。您可以遍历内容以查找这些文件,如下所示。

targets = []
for i in contents:
    if i.endswith(extension):
        targets.append(i)
print(folder, len(contents))

答案 1 :(得分:0)

感谢您的评论和回答,这是我使用的代码(如果它过于接近,请随意将我的问题标记为链接问题的副本):

import os
path = 'path/to/directory'
folders = ([name for name in os.listdir(path)])
targets = []
for folder in folders:
    contents = os.listdir(os.path.join(path,folder))
    for i in contents:
        if i.endswith('.shp'):
            targets.append(i)
    print(folder, len(contents))

print "Total number of files = " + str(len(targets))