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脚本批量删除特定后缀名的文件
- python脚本-指定目录针对特定后缀名文件进行文本内容搜索
- Python_删除/创建指定目录及其下所有子目录的文件,该文件记录当前文件夹的内容
- svn 文件批量删除自动提交脚本(python)
- 涛哥的Python脚本工具箱之批量替换目录所有指定扩展名的文件中的指定字符串
- 备忘:遍历批量替换多目录多文件内容——VBS脚本
- Python删除指定目录下过期文件的2个脚本分享
- Python中删除特定目录下的文件
- Python脚本之批量实现文件内容追加
- 删除windows上特定目录下以*.rar后缀名的python脚本
- Python实现删除当前目录下除当前脚本以外的文件和文件夹实例
- Python批量删除特定文件
- 人生第一份python脚本 ---- 遍历文件夹中文件,删除特定文件中的一行代码
- Python 实现在对一个目录下所有文件,指定某一行之后添加内容(批处理脚本)
- Python批量删除指定目录下的指定类型的文件
- Python实现删除当前目录下除当前脚本以外的文件和文件夹实例
- Python删除指定目录下过期文件的2个脚本分享
- python脚本:搜索某一目录下出现特定字符串的文件
- 批量执行特定文件目录下SQL文件脚本
- 使用Python脚本删除指定文件夹下的指定目录及其文件