Python 脚本 批量删除目录下文件的特定内容

来源:互联网 发布:simnow python 编辑:程序博客网 时间:2024/05/01 00:41
# -*- coding: gbk -*-#/bin/python__author__ = 'yli108'import os,sys,time,codecsreload(sys) sys.setdefaultencoding("gbk")READ_CODEC = 'gbk'HomeDir = os.path.split(os.path.abspath(sys.argv[0]))[0]SP_DIR = 'D:\\Git Surepay\\SUREPAY-CORE\\sp'SP_OUT_DIR = 'D:\\Git Surepay\\SUREPAY-CORE\\sp1'def getfilelist(dir):    '''list all files under the dir'''    filelist = []    for dirpath,dirname,filenames in os.walk(dir):        for name in filenames:            if name.strip().endswith('.tcl'):                tcl = os.path.join(dirpath, name)                print tcl                filelist.append(tcl)    return filelistdef frd(filepath):    ''' Get file context,         and rename it to name.bak        and generate buffer.     '''    Dir, filename = os.path.split(filepath)    file_bk = Dir + '\\' + filename.strip('.tcl')+'_tcl.bak'    file_in = filepath    count =0    buffer = []    if not os.path.isfile(file_in):        print "Can't find "+file_in        return 0,False,buffer    else:        with codecs.open(file_in, 'r', encoding = READ_CODEC) as tcl:            flag = False            Change_flag = False            for line in tcl:                count = count + 1                if line.strip().startswith(r'%% if {$R27_ONLY == "FALSE"} {'):                    flag = True                    Change_flag = True                    count = 1                elif flag and line.strip().startswith(r'%%'):                    count = count + line.strip().count('{') - line.strip().count('}')                    if count == 0:                        flag = False                        line = ''                if not flag:                    buffer.append(line.strip('\n'))        tcl.close()        #os.remove(file_in)        if Change_flag:            pass            #os.rename(file_in,file_bk)        else:            buffer = []        return 1,Change_flag,bufferdef fwt(filepath,buffer):    '''                write buffer to newfile, newfile  use old filename.        for text that between             "%% R27_ONLY == FALSE {} {                ...             %% }        will not be included to new file.    '''    try:        fout = open(filepath+'new','w')        fout.write(''.join(buffer))        fout.close()        return 1    except:        return 0if __name__ == '__main__':    '''Usage: delete_code.py   No parameter'''    file_done = HomeDir + '\\' + 'done_list.txt'    filelist = getfilelist(SP_DIR)        # open record file to see done files.    fd = open(file_done,'r+')    fd_list = fd.readlines()    for f in filelist[56:57]:        if f not in fd_list:            code,c_flag,buffer = frd(f)            if code and c_flag :                if fwt(f,buffer):                    print "Task Success!     " + f                    fd.write(f+'\n')                else:                    print "Write File Fail!!     " + f            elif code and not c_flag:                print "TCL File no need change !    " + f            else:                print "Task Fail!!    " + f      fd.close()

0 0