python統計指定目錄內文件的代碼行數,程序實現統計指定目錄內各個python文件的代碼總行數,注釋行數,空行數,并算出所占百分比
這符合一些公司的小需求,實際代碼量的統計工作
效果如圖
代碼如下:
#coding:utf-8 import os,re #代碼所在目錄 FILE_PATH = './' def analyze_code(codefilesource): ''' 打開一個py文件,統計其中的代碼行數,包括空行和注釋 返回含該文件總行數,注釋行數,空行數的列表 :param codefilesource: :return: ''' total_line = 0 comment_line = 0 blank_line = 0 with open(codefilesource,encoding='gb18030',errors='ignore') as f: lines = f.readlines() total_line = len(lines) line_index = 0 #遍歷每一行 while line_index < total_line: line = lines[line_index] #檢查是否為注釋 if line.startswith("#"): comment_line += 1 elif re.match("\s*'''",line) is not None: comment_line += 1 while re.match(".*'''$",line) is None: line = lines[line_index] comment_line += 1 line_index += 1 #檢查是否為空行 elif line =='\n': blank_line += 1 line_index += 1 print("在%s中:"%codefilesource) print("代碼行數:",total_line) print("注釋行數:",comment_line,"占%0.2f%%"%(comment_line*100/total_line)) print("空行數:", blank_line, "占%0.2f%%"%(blank_line * 100 / total_line)) return [total_line,comment_line,blank_line] def run(FILE_PATH): os.chdir(FILE_PATH) #遍歷py文件 total_lines = 0 total_comment_lines = 0 total_blank_lines = 0 for i in os.listdir(os.getcwd()): if os.path.splitext(i)[1] == '.py': line = analyze_code(i) total_lines,total_comment_lines,total_blank_lines=total_lines+line[0],total_comment_lines+line[1],total_blank_lines+line[2] print("總代碼行數:",total_lines) print("總注釋行數:",total_comment_lines,"占%0.2f%%"%(total_comment_lines*100/total_lines)) print("總空行數:", total_blank_lines, "占%0.2f%%"% (total_blank_lines * 100 / total_lines)) if __name__ == '__main__': run(FILE_PATH)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
