python-统计python文件代码行数

题目:

一个目录里面多个python程序文件,统计一下里面有多少行代码。即分别列出:代码、空行、注释的行数。其中注释包括单行注释(#) 多行注释(’’’/""")

代码:

# -*- coding=utf-8 -*-
# name: nan chen
# date: 2021/3/25 15:03
import os


# 统计代码行数
def count_codes(path):
    # 返回指定的文件夹包含的文件/文件夹的名字的列表
    file_list = os.listdir(path)
    # 改变当前工作路径
    os.chdir(path)
    nn = ("'''", '"""')
    totalcodes, totalnulls, totalnotes = 0, 0, 0
    for file in file_list:
        if file.endswith('.py'):
            total, codes, nulls, notes = 0, 0, 0, 0
            # 标记多行注释
            isMutinotes = False
            lines = open(file, encoding='utf-8').readlines()
            for line1 in lines:
                line = line1.strip()
                if line.startswith('#'):
                    notes += 1
                elif line.startswith(nn):
                    if line.endswith(nn) and len(line) > 3:
                        notes += 1
                        isMutinotes = False
                        continue
                    if not isMutinotes:
                        isMutinotes = True
                        notes += 1
                    elif isMutinotes:
                        isMutinotes = False
                        notes += 1
                elif isMutinotes:
                    notes += 1
                elif not isMutinotes and len(line) == 0:
                    nulls += 1
                else:
                    codes += 1
            total = nulls + codes + notes
            totalcodes = totalcodes + total  # 代码行数
            totalnulls = totalnulls + nulls
            totalnotes = totalnotes + notes
            print("%s 有代码%d行 空行%d行 注释%d行" % (file, total, nulls, notes))
    print("%s目录下python程序文件共有代码%d行 空行%d行 注释%d行" % (path, totalcodes, totalnulls, totalnotes))


if __name__ == '__main__':
    # count_codes("D:\computerVision")
    count_codes("D:\pycode")

结果:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值