統計python代碼行數

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

一、需求

    統計源碼目錄下py文件的代碼行數。

    16a2284fa7175bc6f107b02959024ff6.png


二、腳本分析

    獲取指定目錄下所有的.py文件,對文件進行遍歷;

    讀取每個文件,對文件內容進行遍歷,過濾掉空行和註釋;


三、實現及結果

#coding:utf-8
import os

class 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()

運行結果如下:

cc2ac41637ba3f31728df8ad7e07162a.png


四、總結

    問題:

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

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

    解決方法:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章