實例如下所示:
import osimport string path = "/Users/U/workspace/python learning/show-me-the-code/0007/test/"dir = os.listdir(path) def count(file): total = 0 #總行數 countPound = 0 #注釋行數 countBlank = 0 #空行數 line = open(file,'r',encoding='utf-8') #打開文件,因為注釋有中文所以使用utf-8編碼打開 for li in line.readlines(): #readlines()一次性讀完整個文件 total += 1 if not li.split(): #判斷是否為空行 countBlank +=1 li.strip() if li.startswith('#'): countPound += 1 print(file) print("countBlank:%d" % countBlank) print("countPound:%d" % countPound) print("total:%d" % total) for file in dir: count(path + file)
以上這篇用python統計代碼行的示例(包括空行和注釋)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答