`
chensss2008
  • 浏览: 91623 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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 楼 吕不为 2009-04-16  
import glob,os
if not os.path.exists('new'):
  os.mkdir('new')
for file in glob.glob('*.html'):
  txt=open(file).read()
  txt=txt.replace('....').replace('....').replace('...')
  open(os.path.join(os.getcwd()+'\\new\\',file),'w').write(txt)

相关推荐

Global site tag (gtag.js) - Google Analytics