python统计代码空行与注释

  #_*_coding:utf-8_*_


# 统计代码行数, 空行, 注释.


import os
def code_lines_count(path):
    code_lines = 0
    comm_lines = 0
    space_lines = 0    
    for root,dirs,files in os.walk(path):
        for item in files:                
            file_abs_path = os.path.join(root,item)            
            postfix = os.path.splitext(file_abs_path)[1]
            print(file_abs_path)
            if postfix == '.py':
                #print 'Start: ',file_abs_path
                with open(file_abs_path,encoding='utf-8') as fp:
                    while True:
                        line = fp.readline()
                        if not line:
                            #print 'break here,%r' %line
                            break
                        elif line.strip().startswith('#'):
                            #print '1, here',line
                            comm_lines += 1
                        elif line.strip().startswith("'''") or line.strip().startswith('"""'):
                            comm_lines += 1
                            if line.count('"""') ==1 or line.count("'''") ==1:
                                while True:
                                    line = fp.readline()
                                    #print '4, here',line
                                    comm_lines += 1
                                    if ("'''" in line) or ('"""' in line):
                                        break
                        elif line.strip()=='':
                            #print '5, here',line
                            space_lines += 1
                        else:
                            #print '6, here',line
                            code_lines +=1
                #print 'Done',file_abs_path
    return code_lines,comm_lines,space_lines
#test
print("Code lines: %d\nComments lines: %d\nWhiteSpace lines: %d" %code_lines_count(r'D:\java\pythondemo\src\cn\zcw'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值