欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python统计指定目录内文件的代码行数

时间:2021-03-31 09:12:47|栏目:Python代码|点击:

python统计指定目录内文件的代码行数,程序实现统计指定目录内各个python文件的代码总行数,注释行数,空行数,并算出所占百分比

这符合一些公司的小需求,实际代码量的统计工作

效果如图

代码如下:

#coding:utf-8
import os,re
 
#代码所在目录
FILE_PATH = './'
 
def analyze_code(codefilesource):
  '''
  打开一个py文件,统计其中的代码行数,包括空行和注释
  返回含该文件总行数,注释行数,空行数的列表
  :param codefilesource:
  :return:
  '''
  total_line = 0
  comment_line = 0
  blank_line = 0
  with open(codefilesource,encoding='gb18030',errors='ignore') as f:
    lines = f.readlines()
    total_line = len(lines)
    line_index = 0
    #遍历每一行
    while line_index < total_line:
      line = lines[line_index]
      #检查是否为注释
      if line.startswith("#"):
        comment_line += 1
      elif re.match("\s*'''",line) is not None:
        comment_line += 1
        while re.match(".*'''$",line) is None:
          line = lines[line_index]
          comment_line += 1
          line_index += 1
      #检查是否为空行
      elif line =='\n':
        blank_line += 1
      line_index += 1
  print("在%s中:"%codefilesource)
  print("代码行数:",total_line)
  print("注释行数:",comment_line,"占%0.2f%%"%(comment_line*100/total_line))
  print("空行数:", blank_line, "占%0.2f%%"%(blank_line * 100 / total_line))
  return [total_line,comment_line,blank_line]
def run(FILE_PATH):
  os.chdir(FILE_PATH)
  #遍历py文件
  total_lines = 0
  total_comment_lines = 0
  total_blank_lines = 0
  for i in os.listdir(os.getcwd()):
    if os.path.splitext(i)[1] == '.py':
      line = analyze_code(i)
      total_lines,total_comment_lines,total_blank_lines=total_lines+line[0],total_comment_lines+line[1],total_blank_lines+line[2]
  print("总代码行数:",total_lines)
  print("总注释行数:",total_comment_lines,"占%0.2f%%"%(total_comment_lines*100/total_lines))
  print("总空行数:", total_blank_lines, "占%0.2f%%"% (total_blank_lines * 100 / total_lines))
 
if __name__ == '__main__':
  run(FILE_PATH)

上一篇:mac PyCharm添加Python解释器及添加package路径的方法

栏    目:Python代码

下一篇:浅谈Pycharm的项目文件名是红色的原因及解决方式

本文标题:python统计指定目录内文件的代码行数

本文地址:http://www.codeinn.net/misctech/91546.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有