Python 实现在对一个目录下所有文件,指定某一行之后添加内容(批处理脚本)
1 #folder for output 2 outDir = "D:\\ddd" 3 #After which line start to add new sentence 4 startAdd = 'Telnet WatchFor Fail "ERROR"' 5 #The keyword checked sentence we wanna add 6 ItemAdd = ['Telnet WatchFor Fail "Error"','Telnet WatchFor Fail "error"'] 7 8 9 def changeItems(path,pathout): 10 for filename in os.listdir(path): 11 if os.path.isdir(path + '\\' + filename): 12 if not os.path.exists(outDir + '\\' + filename): 13 os.mkdir(outDir + "\\" + filename) 14 changeItems(path + '\\' + filename,outDir + "\\" + filename ) 15 else: 16 print "input:" , path + "\\" + filename 17 filein = open(path +"\\"+ filename, "rb+") 18 print "output:" , pathout +"\\"+ filename 19 fileout= open(pathout + "\\"+filename,"wb") 20 if(filename.split('.')[-1].lower() == "qar" ): 21 for line in filein.readlines(): 22 if startAdd in line: 23 fileout.write(line+"\n") 24 for item in ItemAdd: 25 fileout.write(item +"\n"+"\n") 26 else: 27 fileout.write(line+"\n") 28 else: 29 bufout=filein.read() 30 fileout.write(bufout) 31 filein.close() 32 fileout.close() 33 import os 34 rootpath = os.path.abspath('.') 35 print rootpath 36 changeItems(rootpath,outDir)
有时候需要批处理对目录下的脚本的制定位置进行修改,可参考哈