【问题标题】:How to get the total number of specific files in a directory containing subdirectories? [duplicate]如何获取包含子目录的目录中特定文件的总数? [复制]
【发布时间】:2017-04-29 16:09:11
【问题描述】:

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

【问题讨论】:

  • 不是另一个字面的副本,但非常接近。添加递归,你就有答案了。
  • @cwallenpoole - 谢谢,我去看看 =)

标签: python


【解决方案1】:

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

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

【讨论】:

  • 非常感谢,您的代码有效;)
【解决方案2】:

感谢 cmets 和回答,这是我使用的代码(如果我的问题太接近,请随时将我的问题标记为链接问题的副本):

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

【讨论】:

  • 我会从 os..path.walk() 函数开始,并且 os.path.splitext() 更干净以()结束.
  • @guidot - 感谢您的评论,但为什么 os.path.splitext()endswith() 更干净?
  • 因为 a) 您明确声明,您想要比较扩展名而不是将其隐藏在字符串中 b) 如果存在名为 .shp 的文件,则副作用更少(unix - 以点开头的样式名称,没有扩展名)。
  • @guidot - 感谢您的提示,我会尝试实施 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 2023-01-04
  • 2015-02-07
  • 1970-01-01
  • 2018-07-23
相关资源
最近更新 更多