統計python程式碼數

來源:互聯網
上載者:User

標籤:python 程式碼數

    addhosts項目已接近尾聲,我很想知道我們寫了多少行代碼。

一、需求

    統計源碼目錄下py檔案的程式碼數。

    650) this.width=650;" src="https://s3.51cto.com/oss/201711/15/16a2284fa7175bc6f107b02959024ff6.png" title="codedir.png" alt="16a2284fa7175bc6f107b02959024ff6.png" />


二、指令碼分析

    擷取指定目錄下所有的.py檔案,對檔案進行遍曆;

    讀取每個檔案,對檔案內容進行遍曆,過濾掉空行和注釋;


三、實現及結果

#coding:utf-8import osclass StatLines(object):    def __init__(self,path):        self.path = path    def stat_lines(self):        file_list = os.listdir(self.path)        os.chdir(self.path)        total = 0        for file in file_list:            if file.endswith(‘.py‘):                lines = open(file, encoding=‘utf-8‘).readlines()                count = 0                for line in lines:                    if line == ‘\n‘:                        continue                    elif line.startswith(‘#‘):                        continue                    else:                        count += 1                total += count                print(‘%s has %d lines‘ %(file,count))        print(‘total lines is: %d‘ %total)if __name__ == ‘__main__‘:    sl = StatLines(‘E:\\Python_Project\\addhost_v2\\addhosts‘)    sl.stat_lines()

運行結果如下:

650) this.width=650;" src="https://s3.51cto.com/oss/201711/15/cc2ac41637ba3f31728df8ad7e07162a.png" title="results.png" alt="cc2ac41637ba3f31728df8ad7e07162a.png" />


四、總結

    問題:

    在執行open(file).readlines()時,遇到了如下錯誤

“UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xaf in position 548: illegal multibyte sequence”

    解決方案:

    在open時,設定encoding=‘utf-8‘後,問題得到解決。

本文出自 “樂學園” 部落格,請務必保留此出處http://2338053.blog.51cto.com/2328053/1982133

統計python程式碼數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.