python遍历当前目录并删除某文件

#coding: utf-8
"""
    this programe is to clear driverlog below this dir
    __author__:the_new_one
"""
import os, traceback

#查找文件名中包含关键词的文件
def search_dir(s, path=os.path.abspath('.'),files = []):
    try:
        for x in os.listdir(path):
            path_now = os.path.join(path, x)
            if os.path.isfile(path_now) and s in os.path.splitext(x)[0]:
                print path_now
                #删除查找到的文件
                os.remove(path_now)
                if x not in files:
                    files.append(x)
            elif os.path.isdir(x):
                search_dir(s=s, path=os.path.join(path_now), files=files)
        return files
    except Exception, e:
        print traceback.format_exc()
        print e

if __name__ == "__main__":
    result = search_dir(s='xxx')

通过遍历当前路径下的文件,判断文件名是否包含s,如果是就删除。

posted @ 2017-05-22 17:02  菲菲菲菲菲常新的新手  阅读(4454)  评论(0编辑  收藏  举报