发布于 2017-09-10 00:27:26 | 167 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python多线程编程,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


这篇文章主要介绍了Python基于正则表达式实现文件内容替换的方法,涉及Python文件、目录及字符串正则替换等相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python基于正则表达式实现文件内容替换的方法。分享给大家供大家参考,具体如下:

最近因为有一个项目需要从普通的服务器移植到SAE,而SAE的thinkphp文件结构和本地测试的有出入,需要把一些html和js的引用路径改成SAE的形式,为了不手工改,特地速成了一下Python的正则表达式和文件操作。主要要求是将某目录下的html和js里面的几个路径变量分别更改成相应的形式,匹配文件名的时候用了正则


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)

希望本文所述对大家Python程序设计有所帮助。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务