細細.魚 发表于 2017-5-7 14:49:04

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'
页: [1]
查看完整版本: python 实现當前文件夾下的批量文件的content replace