Python⽂件去除注释的⽅法本⽂实例讲述了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()
(section,option)#如果⽤getint()则直接读取该数据类型为整数
python正则表达式爬虫return value
def IsPassLine(strLine):
#是否是可以忽略的⾏
#可忽略⾏的正则表达式列表
RegularExpressions=["""/'.*#.*/'""","""/".*#.*/"""",
"""/'/'/'.*#.*/'/'/'""","""/"/"/".*#.*/"/"/""""]
for One in RegularExpressions:
zz=repile(One)
if re.search(zz,strLine)==None:
continue
else:
return True#有匹配则忽略
return False
def ReadFile(FileName):
#读取并处理⽂件
fobj=open(FileName,'r')
adlines()
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+'//'+'','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获取源⽂件夹及⽬标⽂件夹路径
wd()+'//'+PtName+'.ini'
SrcPath=ReadIni(IniPath,PyName,'SrcPath')#源⽂件夹
DescPath=ReadIni(IniPath,PyName,'DescPath')#⽬的⽂件夹
#如果⽬的⽂件夹不存在,创建之
if not ists(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程序设计有所帮助。