第6题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
#!/usr/bin/env python3
# -*- coding : utf-8 -*-
import os
total_lines = 0
total_comment_lines = 0
total_blank_lines = 0
def 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 += blankcnt
if __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)