我正在试图获取以特定扩展名(哪个用户将通过)与路径结尾的所有文件的计数。我们也有子文件夹,因此搜索必须递归。 下面是我正在尝试,但它是抛出错误。请建议差距在哪里。 如果删除if file.endswith(extension):
线然后它给出的所有文件的计数值(它包括与所有扩展名的文件)具有特定扩展名的文件的递归搜索
import os, sys
def fileCount(path, extension):
count = 0
for root, dirs, file in os.walk(path):
if file.endswith(extension):
count += len(file)
return count
print fileCount('/home/export/JobDefinition', '.car')
下面是输出:通过文件小号
$ python test.py
Traceback (most recent call last):
File "test.py", line 11, in <module>
print fileCount('/home/export/JobDefinition', '.car')
File "test.py", line 6, in fileCount
if file.endswith(extension):
AttributeError: 'list' object has no attribute 'endswith'
优秀的答案,并一如既往非常优雅...你也可以使用'len'(但我喜欢总和解决方案:P) –
我把它归结为一行;) – heinst
@JoranBeasley,谢谢,yep len会工作正常,但gen exp避免了需要建立一个列表,除非列表很大,否则可能没有真正的区别。 –