您的位置:首页 > 编程语言 > Python开发

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

2017-01-11 13:52 731 查看
# -*- 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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  脚本 python