#有一个文件夹内存放着代码文件,统计所有文件的代码行,注释行和空行的总数
import os
def j_anno(line):
if line.strip().startswith("#"):
return True
else:
return False
def j_annos(line):
if line.strip().startswith("'''") or line.strip().startswith('"""'):
return True
else:
return False
path='E:/vscode/code/testwork'
code_line=0
comm_line=0
space_line=0
for root,dirs,files in os.walk(path):
for item in files:
f_path=os.path.join(root,item)
f_exten=os.path.splitext(f_path)[1]
if f_exten == '.py':
with open(f_path,'r',encoding='utf-8') as fp:
#print('key:',key)
#print('value:',value)
while True:
line=fp.readline()
if not line:
break
elif j_anno(line):
comm_line +=1
elif j_annos(line):
while True:
line=fp.readline()
if j_annos(line):
break
else:
comm_line +=1
elif line.strip():
code_line+=1
else:
space_line+=1
#test
print('目录:%s总共有:\n%d行代码\n%d行注释\n%d个空行'%(path,code_line,comm_line,space_line))