您的位置:首页 > 编程语言 > Python开发

python简单习题系列6

2014-06-07 16:01 246 查看
写一个脚本统计代码的行数。

由于手工统计代码行数费时费力,不如来一个简单的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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: