统计某目录下所有.py文件代码函数

使用遍历文件的方式,过滤去掉注释行

#coding:utf-8

import os,sys,time
import os.path

class CodeStatistics(object):
    '''
    支持遍历py文件,支持utf-8和gbk两种编码
    '''
    def __init__(self,path):
        self.path = path
        
    def lines_of_file(self,fp):
        '''
        功能:遍历文件对象中代码行数,过滤掉注释行
        '''
        line_result = 0
        flag = False
        for line in fp:
            line = line.strip()
            if (line.startswith('"""') or line.startswith("'''")) and flag == False:
                if len(line) == 3:
                    flag = True
                else:
                    if (line.endswith('"""') or line.endswith("'''")):
                        pass
                continue
            if flag == True:
                if (line.endswith('"""') or line.endswith("'''")):
                    flag = False
            else:
                if line.startswith('#') and not line.startswith('#coding'):
                    continue
                if len(line) != 0:
                    line_result += 1
        return line_result
    
    def read_file(self,file):
        '''
        读取文件,并遍历代码行数
        '''
        try:
            with open(file,'r',encoding='utf-8') as fp:
                result = self.lines_of_file(fp)
                print("{}文件中代码行数为==>:{}行".format(file,result)) #打印到CMD界面直观显示本文件代码数
                return result
        except UnicodeDecodeError:
            try:
                with open(file,'r',encoding='gbk') as fp:
                    result = self.lines_of_file(fp)
                    print("{}文件中代码行数为==>:{}行".format(file,result)) #打印到CMD界面直观显示本文件代码数
                    return result
            except UnicodeDecodeError:
                print('请确认文件"{}"编码是否为utf-8或gbk!'.format(file))
                return 0
    
    def get_lines_of_file_or_dir(self):
        '''
        获取一个py文件或者一个目录下所有py文件的代码行数
        '''
        if os.path.isfile(self.path) and self.path.endswith('.py'):
            return self.read_file(self.path),1 #返回文件代码行数和文件数
        elif os.path.isdir(self.path):
            total_lines = 0
            total_files = 0
            for root,dirs,files in os.walk(self.path):
                for file in files:
                    if file.endswith('.py'):
                        lines = self.read_file(os.path.join(root,file))
                        total_lines += lines
                        total_files += 1
            return total_lines,total_files
    
if __name__ == '__main__':
    now = time.time()
    result = []
    for arg in sys.argv[1:]:
        lines,files = CodeStatistics(arg).get_lines_of_file_or_dir()
        result.append((arg,lines,files))
    print('==============最终统计结果===============')
    for element in result:
        if os.path.isfile(element[0]):
            print('文件"{}"代码行共有:{}行。'.format(element[0],element[1]))
        else:
            print('文件夹"{}"下面共有{}个py文件代码行共有:{}行。'.format(element[0],element[2],element[1]))
    print('totaltime:{:.5f}秒'.format(time.time()-now))

转载于:https://my.oschina.net/u/4006483/blog/3077576

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值