十二、获取路径下的各个py文件的代码行数和注释行数和空格数

import os.path

import re

def mainKeywords(dirPath):

blank, comments, codelines, totalines, count, temp =0,0,0,0,0,0

    f_list = os.listdir(dirPath)#获取目录下所有的文件名

    for iin f_list:

if os.path.splitext(i)[1] =='.py':#分离扩张名,筛选扩张名是.py的文件

            print(i)#打印扩张名是py的文件名

            with open(i,'r',encoding='utf-8')as fp:#打开筛选出来的文件名

                while True:

line = fp.readline()#每次读取一行,返回字符串对象

                    totalines +=1

                    if not line:

break    #如果没有行,直接跳出line

                    elif line.strip().startswith('#'):# line.strip() strip()去除空格或者指定的字符 ,startswith() 检查字符串是否以特定的子字符串开头

                        comments +=1

                    elif line.strip().startswith("'''")or line.strip().startswith('"""'):

comments +=1

                        if line.count('"""') ==1 or line.count("'''") ==1:

while True:

line = fp.readline()

totalines +=1

                                comments +=1

                                if ("'''" in line)or ('"""' in line):

break

                    elif line.strip():

codelines +=1

                    else:

blank +=1

                print('the nuber of totalines is : ' +str(totalines-1))

print('the nuber of comments is : ' +str(comments))

print('the nuber of codelines is : ' +str(codelines))

print('the nuber of blanklines is : ' +str(blank))

blank, comments, codelines, totalines =0,0,0,0

mainKeywords('F:\pyxm\python源代码')

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一.文件基础操作 1.步骤 1).以指定的方式打开文件 2)..关闭文做相关操 3)..关闭文件 fp = o...
    无敌帅帅头阅读 1,904评论 0 0
  • #代码统计工具 1 通过参数指定一个绝对路径,sys.argv 2 如果是文件,就直接统计文件的行数,并打印结果 ...
    公子小白123阅读 4,162评论 0 0
  • Introduction This document gives coding conventions for t...
    wuutiing阅读 10,135评论 0 9
  • 原文 原文下载之后的格式略有点不友好,利用简述的markdown,编辑一下.版权归原作者 PEP Index > ...
    大飞哥阅读 7,288评论 0 0
  • MSSQL 跨库查询(臭要饭的!黑夜) 榨干MS SQL最后一滴血 SQL语句参考及记录集对象详解 关于SQL S...
    碧海生曲阅读 10,993评论 0 1