標籤:path main with etc file imp ota 注釋 while
1.代碼的運行結果:
擷取 指定檔案夾下、指定檔案格式 檔案的: 總程式碼數、總注釋行數(需指定注釋格式)、總空行數;
1 #coding: utf-8 2 import os, re 3 4 # 代碼所在目錄 5 FILE_PATH = ‘./‘ 6 7 def analyze_code(codefilesource): 8 ‘‘‘ 9 開啟一個py檔案,統計其中的程式碼數,包括空行和注釋10 返回含該檔案總行數,注釋行數,空行數的列表11 ‘‘‘12 total_line = 013 comment_line = 014 blank_line = 015 16 with open(codefilesource) as f:17 lines = f.readlines()# [‘import aa‘, ‘if main‘, ‘‘]18 total_line = len(lines)19 line_index = 020 21 # 遍曆每一行22 while line_index < total_line:23 line = lines[line_index]24 # 檢查是否為注釋25 if line.startswith("#"):26 comment_line += 127 # 檢查是否為空白行28 elif line == "\n":29 blank_line += 130 31 line_index += 132 33 print "在%s中:" % codefilesource34 print "程式碼數:", total_line35 print "注釋行數:", comment_line, "占%0.2f%%" % (comment_line*100.0/total_line)36 print "空行數: ", blank_line, "占%0.2f%%" % (blank_line*100.0/total_line)37 38 return [total_line, comment_line, blank_line]39 40 41 def run(FILE_PATH):42 # 切換到code所在目錄43 os.chdir(FILE_PATH)44 # 遍曆該目錄下的py檔案45 total_lines = 046 total_comment_lines = 047 total_blank_lines = 048 49 for i in os.listdir(os.getcwd()):50 if os.path.splitext(i)[1] == ‘.py‘:51 line = analyze_code(i)52 total_lines, total_comment_lines, total_blank_lines = total_lines + line[0], total_comment_lines + line[1], total_blank_lines + line[2]53 54 print "總程式碼數:", total_lines55 print "總注釋行數:", total_comment_lines, "占%0.2f%%" % (total_comment_lines*100.0/total_lines)56 print "總空行數: ", total_blank_lines, "占%0.2f%%" % (total_blank_lines*100.0/total_lines)57 58 59 if __name__ == ‘__main__‘:60 run(FILE_PATH)
python 指令碼(擷取指定檔案夾、指定檔案格式、的程式碼數、注釋行數)