标签:输出 统计 none code roo span 算法 出错 空白行
小练习:
import os import os.path def count_lines(fp): line_number = 0 blank_line_number = 0 code_line_number =0 comment_number = 0 try: for line in fp: line_number+=1 if line.strip()=="": blank_line_number+=1 continue elif line.strip().startswith("#"): comment_number+=1 else: code_line_number+=1 return line_number,blank_line_number,comment_number,code_line_number except: print("统计文件%s代码时候出错" %fp.name) def count_code_line(file_path): if not os.path.exists(file_path): print("文件的路径不存在,请重新输入!") return None line_number = 0 blank_line_number = 0 code_line_number =0 comment_number = 0 try: fp = open(file_path,"r",encoding="gbk") return count_lines(fp) except: fp = open(file_path,"r",encoding="utf-8") return count_lines(fp) #print(count_code_line("e:\\a.txt")) line_number = 0 blank_line_number = 0 code_line_number =0 comment_number = 0 for root, dirs, files in os.walk("e:\\test",topdown=False) : print(u"当前目录:",root) #打印目录绝对路径 for name in files : print(u‘文件名:‘,os.path.join(root,name) )#打印文件绝对路径 file_path = os.path.join(root,name) count_result = count_code_line(file_path) line_number += count_result[0] blank_line_number += count_result[1] code_line_number +=count_result[2] comment_number += count_result[3] print(""" 总行数:%s 空白行数:%s 注释行数:%s 有效代码行数:%s """ %(line_number,blank_line_number,code_line_number, comment_number))
标签:输出 统计 none code roo span 算法 出错 空白行
原文地址:https://www.cnblogs.com/wenm1128/p/11644903.html