在Python中计算具有特定扩展名的文件数 [英] Count number of files with certain extension in Python

查看:146
本文介绍了在Python中计算具有特定扩展名的文件数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python很新,我试图找出最有效的方法来计算特定子目录下的.TIF文件的数量。



做一些搜索,我发现一个例子(我没有测试),声称计数在一个目录中的所有文件:

  file_count = sum(在os.walk(myPath)中的_,_,f的len(f)))


$ b b

这很好,但我只需要计算TIF文件。我的目录将包含其他文件类型,但我只想要计数TIF。



目前我使用下面的代码:


$ b $对于root,dirs,os.walk(myPath)中的文件,b

  tifCounter = 0 

文件中的文件:
如果文件。 endswith('。tif'):
tifCounter + = 1

循环似乎对我过多/昂贵。

解决方案

某些东西必须迭代目录中的所有文件,并查看每个文件名 - 无论是你的代码还是库例程。因此,无论具体的解决方案是什么,他们都将有大致相同的成本。



如果你认为它太多的代码,如果你实际上不需要搜索子目录递归,可以使用 glob 模块:

  tifCounter = len (glob.glob1(myPath,*。tif))


I am fairly new to Python and I am trying to figure out the most efficient way to count the number of .TIF files in a particular sub-directory.

Doing some searching, I found one example (I have not tested), which claimed to count all of the files in a directory:

file_count = sum((len(f) for _, _, f in os.walk(myPath)))

This is fine, but I need to only count TIF files. My directory will contain other files types, but I only want to count TIFs.

Currently I am using the following code:

tifCounter = 0
for root, dirs, files in os.walk(myPath):
    for file in files:    
        if file.endswith('.tif'):
            tifCounter += 1

It works fine, but the looping seems to be excessive/expensive to me. Any way to do this more efficiently?

Thanks.

解决方案

Something has to iterate over all files in the directory, and look at every single file name - whether that's your code or a library routine. So no matter what the specific solution, they will all have roughly the same cost.

If you think it's too much code, and if you don't actually need to search subdirectories recursively, you can use the glob module:

tifCounter = len(glob.glob1(myPath,"*.tif"))

这篇关于在Python中计算具有特定扩展名的文件数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆