python简单习题系列6

写一个脚本统计代码的行数。

由于手工统计代码行数费时费力,不如来一个简单的python 脚本来的快速便捷。顺便练习一下刚刚学习的python语言。

写的只是简单的功能,还是有很多地方需要改进和加强对错误的处理之类。


#codeing=UTF-8
# 根据输入的目录,统计该目录下代码行数

import os
from os import listdir
from os.path import isdir, isfile


def CountAFileLines(fileName):
    file = open(fileName, 'r')
    allLines = file.readlines();
    i = 0
    for li in allLines:
        if li != '':
            i = i+1        
    file.close()
    return i

def CodeCount(in_path):
    # First, check the input path if is valid directory
    try:
        assert(isdir(in_path) == True)
    except AssertionError:
        in_path = None
        print ('The input path is not a valid directory!\n')
        print ('Please input another right path:')

    # list all files or dirs in input directory
    # if is a dir, call back
    # else if is a cpp/h/cs file, count the liens
    line_number = 0
    if(in_path):
        for one in listdir(in_path):
            one = "/".join([in_path, one])
            curNum = 0
            
            if (isdir(one)):                
                curNum = CodeCount(one)
            elif (isfile(one)):
                (filename, extention) = os.path.splitext(one)
                if(extention == '.h' or extention == '.cpp' or extention == '.cs'):
                    #print all calculate files
                    print (one)
                    curNum = CountAFileLines(one)
            line_number = line_number + curNum
    return line_number



inputPathStr = input('Please input the code path you want count: \n')
print ('\n')
print ('List all calculate files: ')
line_number = CodeCount(inputPathStr)
print ('\nAll codes line number is: ', line_number)



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值