可以指定文件夹名称以及其所在的遍历层次 import os target_file_suffixes = ['html', 'htm'] def is_target_file(file_name): split_list = file_name.split('.') file_suffix = split_list[len(split_list) - 1] if file_suffix in target_file_suffixes: return True return False def is_target_dir(target_dir, paths, target_deepth): if target_dir: # has specified dir to search if target_dir in paths: if target_deepth: # has specified number to search if is_target_deepth(target_dir, paths, target_deepth): return True else: return True else: return True def is_target_deepth(target_dir, paths, target_deepth): if paths.index(target_dir) == target_deepth-1: return True def file_count(cur_dir, target_dir = '', target_deepth = 0): target_file_numbers = 0 if os.path.isdir(cur_dir): files = os.listdir(cur_dir) for f in files: cur_item = cur_dir + '/' + f if os.path.isfile(cur_item): paths = cur_item.split('/') if is_target_dir(target_dir, paths, target_deepth): target_file_numbers += is_target_file(f) else: target_file_numbers += file_count(cur_item, target_dir, target_deepth) return target_file_numbers if __name__ == "__main__": test_data_dir = os.getcwd() + 'TestData' target = 'CSSChange' print(file_count(test_data_dir, target))