python小程序-0006

来源:互联网 发布:mybatis sql使用别名 编辑:程序博客网 时间:2024/06/15 00:03

第6题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。

#!/usr/bin/env python3# -*- coding : utf-8 -*-import ostotal_lines = 0total_comment_lines = 0total_blank_lines = 0def analyzefile(filepath):    linecnt = 0    blankcnt = 0    commentcnt = 0    global total_lines    global total_comment_lines    global total_blank_lines    with open(filepath) as f:        for line in f:            #print(str(linecnt)+"   "+line)            line = line.strip()            linecnt += 1            if line == '':                blankcnt += 1            elif line[0] == '#' or line[0] == '/':                commentcnt += 1    total_lines += linecnt    total_comment_lines += commentcnt    total_blank_lines += blankcntif __name__ == '__main__':    dirpath = input("Please input dirpath: ")    for file in os.listdir(dirpath):        filepath = os.path.join(dirpath,file)        if filepath.split('.')[-1] == 'py':            analyzefile(filepath)    print("Total codes line num is %d" % total_lines)    print("Total comment lines num is %d" % total_comment_lines)    print("Total blank lines num is %d" % total_blank_lines)