我试图获取以特定扩展名(用户将通过的)结尾的所有文件的数量以及路径。我们也有子文件夹,因此搜索必须是递归的。以下是我正在尝试的内容,但它抛出错误。请指出差距在哪里。如果我删除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')
Run Code Online (Sandbox Code Playgroud)
下面是输出:
$ 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'
Run Code Online (Sandbox Code Playgroud)
您想要过滤所有文件后的总和:
def fileCount(path, extension):
count = 0
for root, dirs, files in os.walk(path):
count += sum(f.endswith(extension) for f in files)
return count
Run Code Online (Sandbox Code Playgroud)
files返回文件列表,因此sum(f.endswith(extension) for f in files)将为您提供以给定扩展名结尾的所有文件的计数。
或者只返回所有的总和:
def fileCount(path, extension):
return sum(f.endswith(extension) for root, dirs, files in os.walk(path) for f in files)
Run Code Online (Sandbox Code Playgroud)