利用python 統計源碼行數

jopen 9年前發布 | 911 次閱讀 Python

原理先獲取所有文件,然后統計每個文件中代碼的行數,最后將行數相加,思路很簡單。

import os
import os.path
import time
rootdir = '文件路徑'
filelists = []

遍歷文件

def getFile(rootdir): global filelists for parent,dirnames,filenames in os.walk(rootdir): for dirname in dirnames: getFile(os.path.join(parent,dirname)) #嵌套 for filename in filenames:

        #print "filename is:"+ filename  
        filelists.append(os.path.join(parent,filename))

統計一個文件的行數

def countLine(fname): count = 0 for file_line in open(fname).xreadlines(): if file_line != '' and file_line != '\n': #過濾掉空行 count += 1 print fname + '.....' , count return count

if name == 'main' : startTime = time.clock() getFile(rootdir) totalline = 0 for filelist in filelists: totalline = totalline + countLine(filelist) print 'totalline:',totalline print 'done:%0.2f second' % (time.clock() - startTime)</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!