2016-12-14 144 views
0

以下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)) 
+0

不是文本对方的副本,但相当不错。添加递归,你有你的答案。 – cwallenpoole

+0

@cwallenpoole - 谢谢,我会看看=) – Joseph

回答

1

可以在字符串上使用.endswith()函数。这对于识别扩展很方便。你可以遍历内容来找到这些文件,然后如下。

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

非常感谢,您的代码工作;) – Joseph

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)) 
+0

我会开始* os..path.walk()*功能,* os.path.splitext()*比* endswith()*更清洁。 – guidot

+0

@guidot - 感谢您的评论,但为什么_os.path.splitext()_比_endswith()_更清洁? – Joseph

+1

因为)你明确指出,要扩展比较,而不是隐藏在这一串B)副作用少文件是否存在名为* .SHP *(UNIX风格的名称以点开头,没有扩展名意)。 – guidot

相关问题