使用Python简单快速实现统计代码行数

1.程序简介

    这个程序使用来统计文件夹中的所有文件中非空行的行数。代码比较简单易懂,使用递归的方式进行文件夹中所有文件的获取。

2.效果图

使用Python简单快速实现统计代码行数_第1张图片

图2-1


    图2-1 为要测试文件夹的内容,下面来运行一下程序

使用Python简单快速实现统计代码行数_第2张图片

图2-2

    运行程序之后返回文件名和对应的行号,并返回所有文件的总行号,和文件总数量。

3.程序代码

#!-*-coding:utf-8-*-
#author:Terry Lee
#date:2015/11/16 
#
#description:this script is used to exec omret coding lines.
#usage:first param is dir path
#      second param is exclude files array

import os

TOTAL = 0 #total line number
FILENUM = 0 #total file number

class execLine(object):

    #----get all files path under the specified dir-----
    def run(self,dirPath,excludeFiles):
        for fileordir in os.listdir(dirPath):        
            path = os.path.join(dirPath,fileordir)
            if os.path.isfile(path):

                #----exclude the specified files------
                for excludeFile in excludeFiles:
                    if fileordir != excludeFile:
                        line = self.execFileLines(path)
                        global TOTAL
                        TOTAL += line
                        global FILENUM
                        FILENUM += 1
                        print str(FILENUM)+': [filename] '+fileordir+(' '*(50-len(fileordir)))+'[line] '+str(line)
                        
            elif os.path.isdir(path):
                #----if file is dir,use recursion----
                self.run(path,excludeFiles)
    
    #----exec the lines of file,execpt blank line----            
    def execFileLines(self,filepath):
        line = len([ln for ln in open(filepath, 'rt') if ln.strip()])
        return line

    def showTotal(self):
        print "\ntotal file number: "+str(FILENUM)+"\ntotal lines: "+str(TOTAL)
    
execLine = execLine()
execLine.run('C:\\Users\\zhoufm\\Desktop\\test',[''])
execLine.showTotal()

    代码的话我就不多做解释了,相信小伙伴们都能看的懂的,有疑问或者改进的建议也可以评论我。

    在脚本的最后调用run方法进行统计。第一个参数为文件夹路径,就是要统计的项目的文件夹,第二个参数是需要过滤掉的文件名,你们当然不希望把框架自动生成的文件还有一些图片啊什么的都统计进去吧。:)

    测试一下过滤功能,修改下面的代码

execLine.run('C:\\Users\\zhoufm\\Desktop\\test',['1.txt'])

使用Python简单快速实现统计代码行数_第3张图片

    可以发现<1.txt>这个文件被过滤掉了,最后笔者在print文件名和行号的时候加了一个小trick,使得输出看起来比较舒服,我们换一个内容多一些的文件夹试一下。

使用Python简单快速实现统计代码行数_第4张图片

    这样看起来就比较轻松啦。

你可能感兴趣的:(django,python,django,python,脚本)