您的位置:首页 > 编程语言 > Python开发

搜索指定类型文件数量(python)

2011-02-17 16:01 711 查看
可以指定文件夹名称以及其所在的遍历层次

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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: