標籤: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程式碼數