Python 练习册,每天一个小程序(0007)

本文介绍了一种Python脚本的方法,用于统计指定文件夹内所有程序文件的总行数、空行数、注释行数及有效代码行数。通过递归遍历文件夹并分析每个文件的内容来实现。

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

详细题目在https://github.com/Yixiaohan/show-me-the-code上。此次是0007题,统计文件夹内程序文件的行数。

# -*- coding: UTF-8 -*-
import os
import re

#将文件夹中的每个文件目录放入一个列表中
def getFile(directory):
    list = os.listdir(directory)
    fileList = []
    for item in list:
        filepath = os.path.join(directory,item)
        if not os.path.isdir(filepath):
            fileList.append(filepath)
    return fileList

#对于每个程序文件中,读取每一行,如果是换行符则空行数量加1,有#号存在则注释行数加1,其余为普通代码数量加1
def Calculator(fileList):
    null = 0
    annotation = 0
    normal = 0
    for item in fileList:
        with open(item,'r') as file:
            for statement in file.readlines():
                if statement == "\n":
                    null += 1
                elif '#' in statement:
                    annotation += 1
                else:
                    normal += 1
    print 'The total lines is:'+ str(null+annotation+normal)
    print 'The null statement is:'+ str(null)
    print 'The annotation is:'+ str(annotation)
    print 'The statement is:'+ str(normal)

list = getFile('program')
Calculator(list)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值