Python string replacement example

  • 2020-04-02 13:36:41
  • OfStack

After php5.2 upgrade to 5.3, the original & new writing method has been abandoned, can be directly new, in the face of hundreds of PHP files, manual modification is just want to kill, so wrote a script, minutes to do it.


#-*- coding:utf-8 -*- 
#!/usr/bin/python   
import os
# Define the program root directory 
rootpath='D:\wamp\www\erp\app'
def m_replace(path):
 for item in os.listdir(path):
  nowpath=os.path.join(path,item)
  if os.path.isdir(nowpath):
   m_replace(nowpath)
  else:
   if nowpath.find('.php')>0:
    f=open(nowpath,'r+')
    content=f.read().replace('& new ','new ')
    open(nowpath,'w').write(str(content))
    f.close()
if __name__=="__main__":
 m_replace(rootpath)


Related articles: