python 實現當前文件夾下的批量文件的content replace

一直在默默地學習python, 但是隻是作為初級學習者,從來沒有真正應用過。今天工作中剛好有批量file replace content的job, 為了方便自己,提供工作效率,所以也就為自己量身定做了一個tool,順便也體會一下python 在文件處理方面的強大。

當前文件夾下的批量文件的content replace實現

 

代碼如下:

 

#coding=utf-8
# replace string to the other string
# e: replace '../../resource/' to'../resource/resource/'
import re
import glob
import os


cwd = os.getcwd()
FILEPATH = cwd + '\\'+'*.htm'
NEWPATH = cwd + r'\new'
flist = glob.glob(FILEPATH)
for fpath in flist:
    fobj = file(str(fpath))
    strContent = fobj.read()
    strContent = strContent.replace('../../resource/','../resource/resource/')
    strContent = strContent.replace('../css/','../resource/css/')
    strContent = strContent.replace('../../images/','../resource/images/')
    fobj.close()
    if os.path.exists(NEWPATH):       
        print
    else:       
        os.mkdir(NEWPATH) 
   
    newfile = open(NEWPATH +'\\'+ os.path.basename(fpath),'w')
    newfile.write(strContent)
    newfile.close()
    print NEWPATH +'\\'+ os.path.basename(fpath) +'replace successed'

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章