python 统计代码行数

本文档展示了如何使用Python遍历指定目录下所有.py文件,统计代码总行数、空行和注释数量,适用于代码质量检查和维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import os

k_file_extension = '.py'


def get_file_list():
    file_list = [os.path.join(root, file) for root, dirs, files in os.walk(file_path) for file in files if
                 file.endswith(k_file_extension)]
    return file_list


def count_code_lines(file_list):
    count_of_code_lines = 0
    count_of_blank_lines = 0
    count_of_annotation_lines = 0
    for file in file_list:
        with open(file, 'r', encoding='utf-8') as fp:
            content_list = fp.readlines()
            for content in content_list:
                content = content.strip()
                if content == '':
                    count_of_blank_lines += 1
                elif content.startswith('#'):
                    count_of_annotation_lines += 1
                else:
                    count_of_code_lines += 1
    print(f'代码总行数:{count_of_code_lines},代码空行:{count_of_blank_lines},代码注释:{count_of_annotation_lines}')


if __name__ == '__main__':
    file_path = r'D:\test'
    count_code_lines(get_file_list())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值