You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计文件夹及子文件夹中排除.dat格式的文件总数?

代码调整方案

你可以通过增加文件名后缀过滤逻辑实现需求,调整后的代码如下:

import os

directoryPath = r'C:\\Users\\vishns\\Documents\\Python_Code\\Test_Folder'

number_of_files = sum(
    1 for r, d, files in os.walk(directoryPath) for file in files 
    if not file.lower().endswith('.dat')
)

print(number_of_files)

修改说明

  • 替换了原来直接统计len(files)的逻辑,改为逐文件判断后缀后计数
  • 代码中的lower()是为了同时匹配排除大写后缀的.DAT文件,如果你只需要排除严格小写的.dat后缀文件,删除.lower()即可
  • 你也可以使用另一种等价写法,先过滤文件列表再统计长度:
    number_of_files = sum(
        len([f for f in files if not f.lower().endswith('.dat')])
        for r, d, files in os.walk(directoryPath)
    )
    

内容的提问来源于stack exchange,提问作者Sumit Vishnoi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:06:04