python计算代码的行数


import os


file_type = ['py',
             'html',
             'css',
             'js',
             ]


def count_code_nums(file):
    """获取单个文件的行数
    """
    with open(file, mode='rb') as f:
        return len(f.readlines())


def count_code_nums_pro(file):
    """获取单个文件的行数-去注解,utf8代码
    """
    with open(file, mode ='r',encoding='utf-8') as data:
        count, flag = 0, 0    # 代码行数, 开头注解标示
        begin = ('"""', "'''")
        for line in data:
            line2 = line.strip()
            #  以#开头
            if line2.startswith('#'):
                continue
            #  以('"""', "'''") 开头
            elif line2.startswith(begin):
                #  ('"""', "'''") 开头 ,且当前行('"""', "'''")结束 ,跳过计算
                if line2.endswith(begin) and len(line2) > 3:
                    flag = 0
                    continue
                #  ('"""', "'''") 开头 ,没有('"""', "'''")结束,标志没有置上
                elif flag == 0:
                    flag = 1
                #  ('"""', "'''") 开头 ,没有('"""', "'''")结束,标志置上(注解内的注解),跳过计算
                else:
                    flag = 0
                    continue
            # 不是#和('"""', "'''") 开头 ;
            # 以('"""', "'''")结束且标志置上,注解最后一行
            elif flag == 1 and line2.endswith(begin):
                flag = 0
                continue
            else:
                # 不用处理,flag == 1 的中间注释行
                pass
            # 标志没有置上的有效行才计数
            if flag == 0 and line2:
                count += 1
    return count


def get_all_file_in_paths(path, end_with=['py','html','css','js']):
    """获取给定路径下所有子文件路径
    """
    res = []
    for r_path in os.walk(path):
        for f_name in r_path[2]:
            str_list = f_name.rsplit('.', maxsplit=1)
            if str_list.pop() in end_with:
                # print(f_name)
                res.append(os.path.join(r_path[0], f_name))
    return res


def file_path(path, pro_mode=True):
    total_line = 0
    file_list = get_all_file_in_paths(path, end_with=file_type)
    for file in file_list:
        if pro_mode:
            line_num = count_code_nums_pro(file)
        else:
            line_num = count_code_nums(file)
        total_line += line_num
    return total_line


if __name__ == '__main__':

    dir_path = r'C:Pythonsite-packages
obot'
    lines = file_path(dir_path, pro_mode=True)
    # lines = file_path(dir_path, pro_mode=False)
    print('robot is:', lines)



原文地址:https://www.cnblogs.com/amize/p/14584836.html