Python基于正則表達式實現(xiàn)文件內(nèi)容替換的方法
本文實例講述了Python基于正則表達式實現(xiàn)文件內(nèi)容替換的方法。分享給大家供大家參考,具體如下:
最近因為有一個項目需要從普通的服務(wù)器移植到SAE,而SAE的thinkphp文件結(jié)構(gòu)和本地測試的有出入,需要把一些html和js的引用路徑改成SAE的形式,為了不手工改,特地速成了一下Python的正則表達式和文件操作。主要要求是將某目錄下的html和js里面的幾個路徑變量分別更改成相應(yīng)的形式,匹配文件名的時候用了正則
import os
import re
#all file in the directory
filelist = []
#function to traverse the directory
def recurseDir(path):
for i in os.listdir(path):
if os.path.isdir(path + '\\' + i):
recurseDir(path + '\\' + i)
else:
p = path + '\\' + i
print p
filelist.append(p)
#replace the file content
def replace(strFind, strReplace, lines, fileIO):
for s in lines:
if s.find(strFind) != -1:
foutput.write(s)
fileIO.write(s.replace(strFind, strReplace))
rootpath = os.path.abspath('.')
recurseDir(rootpath)
pattern1 = re.compile(r'.+html')
pattern2 = re.compile(r'.+js')
for fileName in filelist:
match1 = pattern1.match(fileName)
match2 = pattern2.match(fileName)
if match1 or match2:
lines = open(fileName).readlines()
fp = open(fileName + '.temp','w')
foutput = open("result.txt", 'w')
foutput.write(fileName)
if match1:
replace('<include file="./Tpl/', '<include file="./App/Tpl/', lines, fp)
if match2:
replace('xxx/index.php', 'index.php', lines, fp)
fp.close()
#delete original file
if os.path.exists(fileName):
os.remove(fileName);
#rename the temp file
os.rename(fileName + '.temp', fileName)
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python正則表達式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
解決Django中調(diào)用keras的模型出現(xiàn)的問題
今天小編就為大家分享一篇解決Django中調(diào)用keras的模型出現(xiàn)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Django使用paginator插件實現(xiàn)翻頁功能的實例
今天小編就為大家分享一篇關(guān)于Django使用paginator插件實現(xiàn)翻頁功能的實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10
python實現(xiàn)DEM數(shù)據(jù)的陰影生成的方法
這篇文章主要介紹了python實現(xiàn)DEM數(shù)據(jù)的陰影生成的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07
pip安裝python庫時報Failed?building?wheel?for?xxx錯誤的解決方法
最近在使用pip安裝python的時候遇到些問題,所以下面這篇文章主要給大家介紹了關(guān)于pip安裝python庫時報Failed?building?wheel?for?xxx錯誤的解決方法,需要的朋友可以參考下2023-01-01

