Code is to be happy
[python]
所有考试都结束了,静下来看看书,想到前几天想统计一下写过的代码行数,今天下午用了点时间弄了一下,代码写的不是很好,凑合看看吧,日后再整理一下.
[python]
#_*_coding:utf_8_
import os
import glob
filefd = open('out.txt', 'w')
def countFileLines(filename):
count = 0
try:
handle = open(filename, 'r')
for eachline in handle:
count += 1
except IOError, e:
print 'file open error', e
wstr = 'file: ' + str(filename) + ' has %d lines' % count
print wstr
filefd.write(str(wstr) + '\n')
return count
def folderCodeLines(folderpath):
count = 0
filetype = ['*.py', '*.c', '*.cpp', '*.java'] #指定需要统计的文件类型的列表
for type in filetype:
#print type
#filefd.write(str(type)+'\n')
filepath = str(folderpath) + '/' + str(type)
for file in glob.glob(filepath):
count += countFileLines(file)
if count != 0:
print folderpath, 'has code %d lines' % count
#wstr = folderpath + 'has code %d lines' % count
#filefd.write(str(wstr)+'\n')
return count
'''''
思路: 例如先进入algorithom,先计算folderCodeLines(),然后用列表folder+'/'+str(L[i])
要不断的解析字符串和合并路径
利用队列进行目录树的层次遍历,每一层的每个结点都进行folderCodeLines的计算
'''
def countCodeLines(startfolders):
#startfolders = 'D:/study/practice/'
queue = []
L = os.listdir(startfolders)
for i in range(len(L)):
ndir = startfolders + '/' + str(L[i])
#print ndir
filefd.write(str(ndir))
queue.append(ndir)
count = 0
while len(queue)!= 0:
sdir = queue.pop()
#print sdir
if os.path.isdir(sdir):
L = os.listdir(sdir)
for i in range(len(L)):
ndir = sdir + '/' + str(L[i])
queue.append(ndir)
count += folderCodeLines(sdir)
print count
return count
startfolders = 'D:/study/practice/'
countCodeLines(startfolders)
def main():
#统计磁盘所有指定类型的文件的代码行数
#startfolders = 'D:/study/practice/'
dirs = ['D:/study/practice/', 'E:/', 'F:/']
for sdir in dirs:
countCodeLines(sdir)
#main()
补充:Web开发 , Python ,