Methods for removing comments from Python files,
This article describes how to remove comments from Python files. Share it with you for your reference. The specific implementation method is as follows:
#! /Usr/bin/python #-*-coding: GBK-*-# writer: xmnathan # comment the import re import OS import ConfigParser Python = 'note' def ReadIni (path, section, option) in The py file: # file path, chapter, keywords # Read ini cf = ConfigParser. configParser () cf. read (path) value = cf. get (section, option) # If getint () is used, the data type is directly read as an integer return value def IsPassLine (strLine ): # Whether the row can be ignored # list of regular expressions of the row that can be ignored RegularExpressions = ["""/'. *#. */'""","""/". *#. */"""","""/'/'/'. *#. */'/'/'""","""/"/"/". *#. */"] For One in RegularExpressions: zz = re. compile (One) if re. search (zz, strLine) = None: continue else: return True # If a match exists, ignore return False def ReadFile (FileName): # Read and process the file fobj = open (FileName, 'R') AllLines = fobj. readlines () fobj. close () NewStr = ''logstr = '/n % 20 s/N' % (FileName. split ('//') [-1]) # output log nline = 0 for eachiline in AllLines: index = eachline. find ('#') # obtain the location index with the comment clause '#' If index =-1 or nline <3 or IsPassLine (eachline): if eachiline. strip ()! = '': # Exclude empty rows NewStr = NewStr + eachiline else: if index! = 0: NewStr = NewStr + eachiline [: index] + '/N' # extract the comment section LogStr + = "ChangeLine: % s/t % s" % (nline, eachline [index:]) nline + = 1 return NewStr, LogStr def MakeCleanFile (SrcPath, DescPath, FileList): fLog = open (DescPath + '// 'employee '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 (): # obtain the source folder and target folder path IniPath = OS from ini. getcwd () + '//' + PtName + '. ini 'srcpath = ReadIni (IniPath, PyName, 'srcpath') # source folder DescPath = ReadIni (IniPath, PyName, 'descpath') # destination folder # If the destination folder does not exist, created 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: configuration file CleanNote. ini format
[CleanNote] SrcPath=E:/test DescPath=E:/test/newfiles
Batch remove comments of the py file in the specified source folder, and generate a copy and a specified destination folder
I hope this article will help you with Python programming.