python 脚本(获取指定文件夹、指定文件格式、的代码行数、注释行数)

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 = 0
13     comment_line = 0
14     blank_line = 0
15 
16     with open(codefilesource) as f:
17         lines = f.readlines()#  ['import aa', 'if main', '']
18         total_line = len(lines)
19         line_index = 0
20 
21         # 遍历每一行
22         while line_index < total_line:
23             line = lines[line_index]
24             # 检查是否为注释
25             if line.startswith("#"):
26                 comment_line += 1
27             # 检查是否为空行
28             elif line == "\n":
29                 blank_line += 1
30 
31             line_index += 1
32 
33     print "在%s中:" % codefilesource
34     print "代码行数:", total_line
35     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 = 0
46     total_comment_lines = 0
47     total_blank_lines = 0
48 
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_lines
55     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)

 

posted on 2016-11-19 19:51  路之遥_其漫漫  阅读(680)  评论(0编辑  收藏  举报

导航