用py簡單的實現了一個統計程式碼的小工具
#/usr/bin/pythonimport os#count the line of a single filedef CountLine(path): tempfile = open(path) res = 0 for lines in tempfile: res += 1 print "%s %d" %(path, res) #output the file path and linestempfile.close() return res#count the total line of a folder, sub folder includeddef TotalLine(path): total = 0 for root, dirs, files in os.walk(path): for item in files: ext = item.split('.') ext = ext[-1] #get the postfix of the file if(ext in ["cpp", "c", "h", "java", "py", "xml", "properties", "php"]): subpath = root + "/" + item total += CountLine(subpath) return totalprint "Input Path"path = "D:\drug\src"print TotalLine(path)
工具簡單到,統計了源碼中所有的行。包括空白行和注釋行。
上面使用了os.walk來遍曆目錄。os.walk會直接列出一個目錄下的所有檔案,包括子目錄的。
下面是用了os.path.listdir來實現。listdir僅僅會列出目前的目錄下的所有目錄和檔案,不會深入到子目錄。
'''Created on 2013-3-11@author: naughty'''import os#===============================================================================# count the line of a single file#===============================================================================def CountLine(path): tempfile = open(path) res = 0 for lines in tempfile: res += 1 print "%s\t\t\t\t\t%d" % (path, res) tempfile.close() return res#===============================================================================# #count the total line of a folder, sub folder included#===============================================================================def TotalLine(path): total = 0 for mfile in os.listdir(path): fullpath = path + "/" + mfile if os.path.isdir(fullpath): total += TotalLine(fullpath) elif os.path.isfile(fullpath): ext = mfile.split(".") ext = ext[-1] if ext in ['c', 'cpp', 'java', 'py']: total += CountLine(fullpath) return totalprint "Input Path"path = "D:/drug/src"print TotalLine(path)