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

本文介绍了一个Python脚本,该脚本用于批量处理指定目录下的TCL文件,通过查找并移除特定条件下的代码段,并保留其余部分,最终生成新的文件。此脚本能够帮助用户高效地管理和更新大量配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: gbk -*-
#/bin/python
__author__ = 'yli108'

import os,sys,time,codecs
reload(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 filelist

def 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,buffer

def 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 0

if __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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值