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

1.程序简介

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

2.效果图

163113_ColM_255944.jpg

图2-1


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

163114_E3s8_255944.jpg

图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'])

164838_j8ug_255944.jpg

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

165825_qysE_255944.jpg

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

转载于:https://my.oschina.net/u/255944/blog/530997

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值