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)文章
解決pandas報錯'DataFrame' object has no
這篇文章主要介紹了解決pandas報錯'DataFrame' object has no attribute 'as_matrix'問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08Python的Flask框架中Flask-Admin庫的簡單入門指引
這篇文章主要介紹了一個Python的Flask框架中Flask-Admin庫簡單入門的指引,包括介紹和簡單的部署等,需要的朋友可以參考下2015-04-04python實現(xiàn)根據(jù)月份和日期得到星座的方法
這篇文章主要介紹了python實現(xiàn)根據(jù)月份和日期得到星座的方法,涉及Python操作字符串及數(shù)組的技巧,非常具有實用價值,需要的朋友可以參考下2015-03-03