Python批量替换文件内容,支持嵌套文件夹
1 import os
2 path="./"
3 for root,dirs,files in os.walk(path):
4 for name in files:
5 #print name
6 if name.endswith(".html"):
7 #print root,dirs,name
8 filename=root+"/"+name
9 f=open(filename,"r")
10 filecontent=""
11 line=f.readline()
12 while line:
13 l=line.replace(":8081/arcgis_js_api","/arcgisapi")
14 filecontent=filecontent+l
15 line=f.readline()
16 f.close()
17 f2=file(filename,"w")
18 f2.writelines(filecontent)
19 f2.close()
import os
import re
#list files
def listFiles(dirPath):
fileList=[]
for root,dirs,files in os.walk(dirPath):
for fileObj in files:
fileList.append(os.path.join(root,fileObj))
return fileList
def main():
fileDir = "./"
regex = ur'FUNC_SYS_ADD_ACCDETAIL'
fileList = listFiles(fileDir)
for fileObj in fileList:
name = fileObj
if name.endswith(".html"):
print name
f = open(fileObj,'r+')
all_the_lines=f.readlines()
f.seek(0)
f.truncate()
for line in all_the_lines:
f.write(line.replace('https://js.arcgis.com/4.8/','https://gis01.leechg.com/jsapi/4.8/'))
f.close()
if __name__=='__main__':
main()