|
5鱼币
此代码无法统计文件中代码量,不知何处出现问题,还请大佬赐教
- import easygui as e
- import os
- def sum_lines(file):
- lines = 0
- with open(file) as f:
- try:
- for e in f:
- lines += 1
- except UnicodeDecodeError:
- pass
-
-
- return lines
- def seach_file(file_name):
-
- count=b=c=a=0
- file = os.walk(file_name)
- for each in file:
- for i in each[2]:
- file_new = os.path.join(each[0],i)
- num = sum_lines(file_new)
- if os.path.splitext(i) == '.c':
- count += 1
- b += num
- if os.path.splitext(i) == '.py':
- c += 1
- a += num
- total = b + a
- msg = '【.c】源文件%d个,源代码%d行\n【.py】源文件%d个,源代码%d行'%(count,b,c,a)
- title = '您目前共累计编写%d行代码,完成进度:%.2f%%\n离10万行代码还差%d行,请继续努力!'%(total,total/100000,100000-total)
- e.msgbox(msg,title)
- e.msgbox("请打开您存放所有代码的文件夹……","统计代码量")
- path = e.diropenbox("请选择您的代码库")
- seach_file(path)
-
复制代码
本帖最后由 isdkz 于 2022-2-18 13:20 编辑
- >>> help('os.path.splitext')
- Help on function splitext in os.path:
- os.path.splitext = splitext(p)
- Split the extension from a pathname.
- Extension is everything from the last dot to the end, ignoring
- leading dots. Returns "(root, ext)"; ext may be empty.
- >>>
复制代码
要善用 help() 函数,还有学习英语很重要
从上面可以看到 Returns "(root, ext)",splitext返回的是一个元组,元组的第二个元素才是扩展名,
所以改成下面这样:
- import easygui as e
- import os
- def sum_lines(file):
- lines = 0
- with open(file) as f:
- try:
- for e in f:
- lines += 1
- except UnicodeDecodeError:
- pass
-
-
- return lines
- def seach_file(file_name):
-
- count=b=c=a=0
- file = os.walk(file_name)
- for each in file:
- for i in each[2]:
- file_new = os.path.join(each[0],i)
- num = sum_lines(file_new)
- if os.path.splitext(i)[1] == '.c': # 因为splittext返回的是一个元组,所以加上[1]
- count += 1
- b += num
- if os.path.splitext(i)[1] == '.py': # 加上[1]
- c += 1
- a += num
- total = b + a
- msg = '【.c】源文件%d个,源代码%d行\n【.py】源文件%d个,源代码%d行'%(count,b,c,a)
- title = '您目前共累计编写%d行代码,完成进度:%.2f%%\n离10万行代码还差%d行,请继续努力!'%(total,total/100000,100000-total)
- e.msgbox(msg,title)
- e.msgbox("请打开您存放所有代码的文件夹……","统计代码量")
- path = e.diropenbox("请选择您的代码库")
- seach_file(path)
-
复制代码
|
最佳答案
查看完整内容
要善用 help() 函数,还有学习英语很重要
从上面可以看到 Returns "(root, ext)",splitext返回的是一个元组,元组的第二个元素才是扩展名,
所以改成下面这样:
|