In Python, we often want to count the number of lines of code in a project. However, it may not be that simple if we want to improve the statistical functions, today, let's take a look at how to use python to implement a code line statistical tool.
Idea: first obtain all files, then count the number of lines of code in each file, and finally add the number of lines.
Implemented functions:
Count the number of lines in each file;
The total number of rows;
Count the running time;
You can specify the statistic file type to exclude file types that do not require statistics;
Recursively count the number of objects in a folder that contains subfolders;
Exclude empty rows;
# Coding = utf-8import osimport timebasedir = '/root/script' filelists = [] # specify the file type whitelist = ['php', 'py'] # traverse the file, recursively traverse all def getFile (basedir) in the folder: global filelists for parent, dirnames, filenames in OS. walk (basedir): # for dirname in dirnames: # getFile (OS. path. join (parent, dirname) # recursion for filename in filenames: ext = filename. split ('. ') [-1] # only count the specified file type, skipping some log and cache files if ext in whitelist: filelis Ts. append (OS. path. join (parent, filename) # count the number of lines in a file. def countLine (fname): count = 0 for file_line in open (fname ). xreadlines (): if file_line! = ''And file_line! = '\ N': # filter out empty rows: 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)
Result:
[root@pythontab 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[root@pythontab script]#
It is very convenient to count only php and python files.
In fact, you can also make improvements on this basis, such as excluding comments.