1 import easygui as g 2 import os 3 4 def show_result(path): 5 text='' 6 total=0 7 for each_ext in ext_dict: 8 total += ext_dict[each_ext] 9 text += '【%s】源文件有【%d】个,代码【%d】行 '% (each_ext,ext_list[each_ext],ext_dict[each_ext]) 10 11 msg = '您目前累计编写了【%d】行代码,完成进度:【%.2f%%】,离10万行代码还差【%d】,请继续努力!' % (total,total/1000,100000-total) 12 title ='统计结果' 13 g.textbox(msg,title,text) 14 15 16 def calc_line(file_name): 17 lines = 0 18 with open(file_name) as f: 19 try: 20 for each_line in f: 21 lines+=1 22 except UnicodeDecodeError: 23 pass #遇到不兼容情况则继续 24 return lines #返回计算的行数 25 26 27 def search_file(start_dir): 28 os.chdir(start_dir) 29 30 for each_file in os.listdir(os.curdir):#遍历当前目录下的每一个文件 31 32 if os.path.isfile(each_file):#如果是一个文件 33 ext = os.path.splitext(each_file)[1]#取其扩展名 34 if ext in target:# 如果扩展名在目标中 35 lines = calc_line(each_file)#打开这个文件并计算行数 36 37 try: 38 ext_dict[ext] += lines #扩展名的字典 如果扩展名不存在则新建一个并且赋值lines 39 except KeyError: 40 ext_dict[ext] = lines 41 try: 42 ext_list[ext] += 1 #记录源文件有多少个,区别于记录多少行的字典 43 except KeyError: 44 ext_list[ext] = 1 45 46 if os.path.isdir(each_file):#如果是目录,则创造递归 47 search_file(each_file) 48 os.chdir(os.pardir)#递归完成返回上一层目录 49 50 51 def choice_path(): 52 msg = '请选择您的代码库' 53 title = '浏览您的文件夹' 54 55 path = g.diropenbox(msg,title) 56 return path 57 58 59 60 target=['.py','.c'] 61 62 ext_dict={} 63 ext_list={} 64 path = choice_path() 65 search_file(path) 66 show_result(path)