黑松山资源网 Design By www.paidiu.com
本文实例讲述了Python文件去除注释的方法。分享给大家供大家参考。具体实现方法如下:
#!/usr/bin/python # -*- coding: GBK -*- #writer:xmnathan #py文件去注释 import re import os import ConfigParser Python='CleanNote' def ReadIni(path,section,option):#文件路径,章节,关键词 #读取ini cf=ConfigParser.ConfigParser() cf.read(path) value=cf.get(section,option)#如果用getint()则直接读取该数据类型为整数 return value def IsPassLine(strLine): #是否是可以忽略的行 #可忽略行的正则表达式列表 RegularExpressions=["""/'.*#.*/'""","""/".*#.*/"""", """/'/'/'.*#.*/'/'/'""","""/"/"/".*#.*/"/"/""""] for One in RegularExpressions: zz=re.compile(One) if re.search(zz,strLine)==None: continue else: return True#有匹配 则忽略 return False def ReadFile(FileName): #读取并处理文件 fobj=open(FileName,'r') AllLines=fobj.readlines() fobj.close() NewStr='' LogStr='/n%20s/n'%(FileName.split('//')[-1])#输出的日志 nline=0 for eachiline in AllLines: index=eachline.find('#')#获取带注释句‘#'的位置索引 if index==-1 or nline<3 or IsPassLine(eachline): if eachiline.strip()!='':#排除纯空的行 NewStr=NewStr+eachiline else: if index!=0: NewStr=NewStr+eachiline[:index]+'/n'#截取后面的注释部分 LogStr+="ChangeLine: %s/t%s"%(nline,eachline[index:]) nline+=1 return NewStr,LogStr def MakeCleanFile(SrcPath,DescPath,FileList): fLog=open(DescPath+'//'+'CleanNoteLog.txt','w') for File in FileList: curStr,LogStr=ReadFile(SrcPath+'//'+File) fNew=open(DescPath+'//'+File,'w') fNew=write(curStr) fNew.close() fLog.write(LogStr) fLog.close() def Main(): #从ini获取源文件夹及目标文件夹路径 IniPath=os.getcwd()+'//'+PtName+'.ini' SrcPath=ReadIni(IniPath,PyName,'SrcPath')#源文件夹 DescPath=ReadIni(IniPath,PyName,'DescPath')#目的文件夹 #如果目的文件夹不存在,创建之 if not os.path.exists(DescPath): os.makedirs(DescPath) FileList=[] for files in os.walk(SrcPath): for FileName in files[2]: if FileName.split('.')[-1]=='py': FileList.append(FileName) MakeCleanFile(SrcPath,DescPath,FileList) if __name__=='__main__': Main() print '>End<<<' os.system('pause')
ps:配置文件CleanNote.ini的格式
[CleanNote] SrcPath=E:/test DescPath=E:/test/newfiles
批量去除指定源文件夹中的py文件的注释,并生成拷贝与指定目的文件夹
希望本文所述对大家的Python程序设计有所帮助。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 【原神手游】5.1版本更新维护预告
- 李锦华.1987-日与夜(LP版)【SOLO】【WAV+CUE】
- 伍珂玥.2014-伍珂玥【湾彩星辰】【FLAC分轨】
- 吕方.2001-旧情人·老情歌精选2CD【华纳】【WAV+CUE】
- 《星际战士2》¥219,《100% 鲜橙汁》¥7
- 手办鉴赏室:少女眼神颇有杀意!连衣裙勾勒傲人轮廓
- 未来可期的二次元大逃杀游戏——《白厄战境》简评
- 炉石传说死亡骑士卡组怎么搭配 死亡骑士最新卡组2024推荐
- 魔兽世界地下堡珍玩怎么升级 地下堡珍玩升级方法攻略分享
- 魔兽世界怎么获得泽克维尔的残血珍玩 泽克维尔的残血珍玩获取方式
- FrankSinatra-StrangersInTheNight(1966Jazz)[Flac24-96]
- 大原樱子《CAMON+5thAnniversaryBest~》2CD[24-96]flac
- Isgaard2003-GoldenKey(LimitedEdition)【WAV+CUE】
- 《合金装备3RE》伊娃定妆照公布:没被政确太好了
- 石家庄新增《黑神话:悟空》墙绘:小狐狸萍萍