要求一:递归搜索各个文件夹
要求二:显示各个类型的源文件和源代码数量
要求三:显示总行数和百分比
注意点:访问不存在键时 字典的异常处理
递归访问文件调用步骤
#统计代码量
import easygui as g
import os
file_list={}
source_list={}
target = ['.c', '.cpp', '.py', '.cc', '.java', '.pas', '.asm', '.xml']
def calc_count(file_name):
lines=0
with open(file_name) as f:
try:
for each_line in f:
lines+=1
except(UnicodeDecodeError, PermissionError):
pass
return lines
def show_result(dirpath):
total=0
text=''
for i in source_list:
total+=source_list[i]
text+='【%s】源文件%d个,源代码%d行\n'%(i,file_list[i],source_list[i])
msg="您一共累计编写%d行代码"
def search_file(start_dir):
'''递归搜索文件夹'''
os.chdir(start_dir)
for each_file in os.listdir(os.curdir):
file_type=os.path.splitext(each_file)[1]
if file_type in target:
lines_count=calc_count(each_file)
try:
#直接访问字典中不存在的键会报错,赋值不会报错
#例如:32不存在dict{}的键中,dict[32]会报错,但dict[32]='赞'不会报错会创建新的键值对
file_list[file_type] += 1
except KeyError:
file_list[file_type] = 1
try:
source_list[file_type] += lines_count
except KeyError:
source_list[file_type] = lines_count
if os.path.isdir(each_file):
#递归调用
search_file(each_file)
#重要!调用后返回上一级目录
os.chdir(os.pardir)
g.msgbox("请打开您存放所有代码的文件夹......", "统计代码量")
path = g.diropenbox("请选择您的代码库:")
search_file(path)
show_result(start_dir)