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,如果是就刪除。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM