Python程式碼統計

來源:互聯網
上載者:User

用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)

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.