本文實(shí)例講述了Python文件去除注釋的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
#!/usr/bin/python # -*- coding: GBK -*- #writer:xmnathan #py文件去注釋 import re import os import ConfigParser Python='CleanNote' def ReadIni(path,section,option):#文件路徑,章節(jié),關(guān)鍵詞   #讀取ini  cf=ConfigParser.ConfigParser()   cf.read(path)   value=cf.get(section,option)#如果用getint()則直接讀取該數(shù)據(jù)類型為整數(shù)   return value def IsPassLine(strLine):   #是否是可以忽略的行   #可忽略行的正則表達(dá)式列表   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獲取源文件夾及目標(biāo)文件夾路徑   IniPath=os.getcwd()+'//'+PtName+'.ini'   SrcPath=ReadIni(IniPath,PyName,'SrcPath')#源文件夾   DescPath=ReadIni(IniPath,PyName,'DescPath')#目的文件夾   #如果目的文件夾不存在,創(chuàng)建之   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程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選