第 0007 题: 有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
# -*- coding:utf-8 -*-
import os def countCode(path):
if not os.path.exists(path):
print('路径不存在!')
else:
fileNameList = os.listdir(path)
for fileName in fileNameList:
nbspCount = 0
commentCount = 0
codeCount = 0
multiCommentEndFlag = 0
if ('.py' in fileName) and (fileName[-3:] == '.py'):
with open(path+'\\'+fileName,encoding='utf-8') as f:
code = f.readlines()
for i in code:
codeCount += 1
i = i.strip()
if multiCommentEndFlag == 1: #多行注释中内容
commentCount += 1
if len(i) >= 3 and (i[-3:] == '\'\'\'' or i[-3:] == '\"\"\"'): #多行注释结尾
multiCommentEndFlag = 0
elif len(i) >= 3 and (i[0:3] == '\'\'\'' or i[-3:] == '\"\"\"'): #多行注释开头
commentCount += 1
multiCommentEndFlag = 1
if len(i) > 3 and (i[-3:] == '\'\'\'' or i[-3:] == '\"\"\"'): #多行注释符在同一行的情况
multiCommentEndFlag = 0
elif i == '': #空行
nbspCount += 1
elif len(i) >= 1 and i[0] == '#': #单行注释(#)
commentCount += 1
print('{0}中代码行数为:{1},其中空行数:{2},注释数:{3}'.format(fileName, codeCount, nbspCount, commentCount)) if __name__ == '__main__':
countCode(r'C:\Users\Admin\PycharmProjects\untitled\python每日一练')