Count number of files with certain extension in Python

前端 未结 5 759
一整个雨季
一整个雨季 2020-12-12 23:55

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,

5条回答
  •  执念已碎
    2020-12-13 00:50

    If you do need to search recursively, or for some other reason don't want to use the glob module, you could use

    file_count = sum(len(f for f in fs if f.lower().endswith('.tif')) for _, _, fs in os.walk(myPath))
    

    This is the "Pythonic" way to adapt the example you found for your purposes. But it's not going to be significantly faster or more efficient than the loop you've been using; it's just a really compact syntax for more or less the same thing.

提交回复
热议问题