In the process of working or learning code, we often want to know how many lines of code we have written, and today we write a script in the project environment to count the number of project code.
Function:
1. Total number of statistics code rows
2. Counting Empty rows
3. Count the number of comment lines
#Coding=utf-8ImportOS#define the directory where the code residesBase_path ='/home/yhl/workspace/xtp_test'#all the py files are counted in the specified directory and returned as a listdefCollect_files (dir): FileList= [] forParent,dirnames,filenamesinchOs.walk (dir): forFileNameinchFilenames:ifFilename.endswith ('. PY'): #To add a file name and directory name to an absolute path, added to the listfilelist.append (Os.path.join (parent,filename))returnfilelist#to calculate the number of lines of code within a single filedefcalc_linenum (file): with open (file) as Fp:content_list=fp.readlines () code_num= 0#current File code line count variableBlank_num = 0#The current file empty row count variableAnnotate_num =0#Current File Comment Row count variable forContentinchcontent_list:content=Content.strip ()#Statistics blank line ifContent = ="': Blank_num+ = 1#Statistical Comment lines elifContent.startswith ('#'): Annotate_num+ = 1#Statistical Code Lines Else: Code_num+ = 1#Returns the number of lines of code, number of empty lines, number of comment lines returnCode_num,blank_num,annotate_numif __name__=='__main__': Files=collect_files (base_path) Total_code_num= 0#statistics file code line count variableTotal_blank_num = 0#statistics file empty line count variableTotal_annotate_num = 0#Statistics file Comment row count variable forFinchFiles:code_num, Blank_num, Annotate_num=Calc_linenum (f) Total_code_num+=Code_num Total_blank_num+=Blank_num Total_annotate_num+=Annotate_numPrintu ' code total number of rows:%s '% total_code_numPrintu ' empty row total number of rows is:%s '% total_blank_numPrintU ' comment line total rows:%s '% Total_annotate_num
Execution Result:
Python Statistics code Total rows (lines of code, blank lines, comment lines)