旧版python 35讲最后一题
import easygui as gimport os
def show_result(start_dir):
lines = 0
total = 0
text = ''
for i in source_list:
lines = source_list
total += lines
text += '【%s】源文件%d个,源代码%d行\n'%(i,file_list,lines)
title = '统计结果'
msg = '您目前共积累编写了%d行代码,完成进度:%.2f%%\n离10万行代码还差%d行,请继续努力!'%(total,total/1000,100000-total)
g.textbox(msg,title,text)
def calc_code(file_name):
lines = 0
with open(file_name) as f:
print('正在分析文件:%s...'%(file_name))
try:
for each_line in f:
lines += 1
except UnicodeDecodeError:
pass# 不可避免会遇到格式不兼容的文件,这里忽略掉....
return
def search_file(start_dir):
os.chdir(start_dir)
for each_file in os.listdir(os.curdir):
ext = os.path.splitext(each_file)
if ext in target:
lines = calc_code(each_file)#统计行数
#还记得异常处理的用法吗?如果字典中不存在,抛出KeyError,则添加字典键
#统计文件数
try:
file_list += 1
except KeyError:
file_list = 1
#统计源代码行数
try:
source_list += lines
except KeyError:
source_list = lines
if os.path.isdir(each_file):
search_file(each_file)#递归调用
os.chdir(os.pardir)#递归调用后切记返回上层目录
target = ['.c','.cpp','.py','.cc','.java','.pas','.asm']
file_list = {}
source_list ={}
g.msgbox('请打开您存放所有代码的文件夹......','统计代码数量')
path = g.diropenbox('请选择您的代码库:')
search_file(path)
show_result(path)
Traceback (most recent call last):
File "D:\python练习\easygui\十万行代码.py", line 66, in <module>
search_file(path)
File "D:\python练习\easygui\十万行代码.py", line 48, in search_file
source_list += lines
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'NoneType'
这个报错是什么原因呢,求大佬解答
可能是你那个文件里没有内容
返回None def calc_code(file_name):
lines = 0
with open(file_name) as f:
print('正在分析文件:%s...'%(file_name))
try:
for each_line in f:
lines += 1
except UnicodeDecodeError:
pass# 不可避免会遇到格式不兼容的文件,这里忽略掉....
return
return的是个空值,应该写return lines fc5igm 发表于 2021-6-19 14:17
return的是个空值,应该写return lines
ok,解决了,谢谢啦
页:
[1]