伟的博客 研发工程师

python批量替换文件内容脚本2009-02-4

2011-03-09

Python代码 #!/usr/bin/python #--coding=utf-8-- import os,sys,re,time; odir = raw_input(‘请输入目录:’); ext = raw_input(‘需要替换的文件后缀:’); sta = raw_input(‘请输入正则表达式:’); strb = raw_input(‘替换厚的字符串:’); os.chdir(odir); c1 = os.walk(os.getcwd()); filelist = []; stra = re.compile(sta,re.DOTALL); for c2 in c1: for c3 in c2[2]: c4 = os.path.join(c2[0],c3); c5 = os.path.splitext(c4); if c5[1] == ext: filelist.append(c4); else: pass; print filelist; for filename in filelist: fileread = open(filename,’r’); filer = fileread.read(); sub = re.sub(stra,strb,filer,0); #替换stra 为 strb fileread.close(); fileok = open(filename,’w’); fileok.write(sub); fileok.close(); print filename,’替换成功!’;


Comments