我正在試圖獲取以特定擴展名(哪個用戶將通過)與路徑結尾的所有文件的計數。我們也有子文件夾,因此搜索必須遞歸。 下面是我正在嘗試,但它是拋出錯誤。請建議差距在哪裏。 如果刪除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避免了需要建立一個列表,除非列表很大,否則可能沒有真正的區別。 –