提问者:小点点

如何使用文件扩展名(例如“。json”)计算包括嵌套文件夹在内的目录中的文件总数


我需要统计目录中的。json文件总数,包括嵌套文件夹。 我试过了

json_file_count = 0 
for roots,dirs, files in os.walk(path)
    for json_file_count in files:
        if os.path.splitext(n)[1] == '.json'
print(json_file_count)

它显示所有file.json文件名。 我需要整数的总数。 我已经尝试了len()

print(len(json_file_count))

但它只计算文件名中包含的字数

当我尝试json_file_count+=files

但它显示类型错误:必须是字符串,而不是int

请帮帮我。 任何帮助都非常感激。 我绝望了。。。。 :'(


共2个答案

匿名用户

这应该可以做到:

json_file_count = 0 
for roots,dirs, files in os.walk(path)
    for file in files:
        if os.path.splitext(file)[1] == '.json':
            json_file_count += 1   
            
print(json_file_count)

您的代码不能工作的原因是,请看下面这个:

for json_file_count in files:

您假定JSON_FILE_COUNT是一个数字,但实际上,它是文件的名称。 我相信你想做的是

for json_file_count in range(1, len(files)+1):

实际上,这是说不通的。

匿名用户

from pathlib import Path

number_of_jsons = len(Path("path/to/dir").rglob("*.json"))