使用Python在指定目录搜索指定文件名

# -*- coding: utf-8 -*-
'''
Created on 2014年12月1日

@author: zhrb
'''


import os

count = 0



    
def search(dstDir,fileName):
    global count
    #files = [os.path.join(dstDir,x) for x in os.listdir(dstDir)]
    for y in os.listdir(dstDir):
        absPath = os.path.join(dstDir,y)
        if os.path.isdir(absPath):
            try:
                search(absPath,fileName)
            except BaseException, e:
                continue
            
        elif (os.path.isfile(absPath) and os.path.split(absPath)[1].lower()==fileName.lower()):
            count +=1
            print('found %s '%absPath.decode('gbk').encode('utf-8'))

search('d:\\','1.jpg')
print("%d founded"%count)

编程技巧