We often want to count the number of lines of code in a project, but it might not be so easy to think of a statistical function, and today we'll look at how to implement a code-line statistics tool using Python.
Idea: Get all the files first, then count the number of lines of code in each file, and finally add the number of rows.
The functions implemented:
Count the number of rows per file;
Statistics total number of rows;
Statistic running time;
Support for specifying statistical file types, excluding file types that do not want to be counted;
The number of rows of files under the recursive Statistics folder, including the sub-components;
Exclude empty lines;
# coding=utf-8import osimport timebasedir = '/root/script ' filelists = []# Specify the file type you want to count whitelist = [' php ', ' py '] #遍历文件, recursively traverse all def getfile in the folder (Basedir): global filelists for parent,dirnames,filenames In os.walk (basedir): #for dirname in Dirnames: # getfile (Os.path.join (Parent, dirname)) #递归 for filename in filenames: ext = filename.split ('. ') [-1] #只统计指定的文件类型, skip some log and cache files if ext in whitelist: &nbSp; filelists.append (Os.path.join (parent,filename)) # Count the number of rows in a file Def countline (fname): count = 0 for file_line in open (fname). Xreadlines (): if file_line != ' and file_line != ' \ n ': #过滤掉空行 count += 1 print fname + '----' , count return countif __name__ == ' __main__ ' : starttime = time.clock () getfile (Basedir) totalline = 0 for filelist in filelists: totalline = totalline + Countline (filelist) print ' total lines: ',totalline print ' done! cost time: %0.2f second ' % (Time.clock () - starttime)
Results:
[email protected] script]# python countcodeline.py/root/script/test/gametest.php----16/root/script/smtp.php---- 284/root/script/gametest.php----16/root/script/countcodeline.py----33/root/script/sendmail.php----17/root/ script/test/gametest.php----16total lines:382done! Cost time:0.00 Second[[email protected] script]#
It is very convenient to only count PHP and Python files.
Python implementation code line counting tool