Python uses regular expressions to replace file content,
This example describes how to replace the file content in Python based on regular expressions. We will share this with you for your reference. The details are as follows:
Recently, because a project needs to be transplanted from a common server to SAE, And the thinkphp file structure of SAE is different from that of local tests, some html and js reference paths need to be changed to the SAE format, to avoid manual modification, we have made Python Regular Expressions and file operations quickly. The main requirement is to change the PATH variables in html and js under a directory to the corresponding form, and use regular expressions when matching the file name.
import osimport re#all file in the directoryfilelist = []#function to traverse the directorydef 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 contentdef 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: here we will provide two very convenient Regular Expression tools for your reference:
JavaScript Regular Expression online testing tool:
Http://tools.jb51.net/regex/javascript
Regular Expression generation tool:
Http://tools.jb51.net/regex/create_reg