用python统计代码行的示例(包括空行和注释)

yipeiwu_com5年前Python基础

实例如下所示:

import os
import string
 
path = "/Users/U/workspace/python learning/show-me-the-code/0007/test/"
dir = os.listdir(path)
 
def count(file):
  total = 0 #总行数
  countPound = 0 #注释行数
  countBlank = 0 #空行数
  line = open(file,'r',encoding='utf-8') #打开文件,因为注释有中文所以使用utf-8编码打开
  for li in line.readlines(): #readlines()一次性读完整个文件
    total += 1
    if not li.split(): #判断是否为空行
      countBlank +=1
    li.strip()
    if li.startswith('#'):
      countPound += 1
  print(file)
  print("countBlank:%d" % countBlank)
  print("countPound:%d" % countPound)
  print("total:%d" % total)
 
for file in dir:
  count(path + file)

以上这篇用python统计代码行的示例(包括空行和注释)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pandas DataFrame数据转为list的方法

首先使用np.array()函数把DataFrame转化为np.ndarray(),再利用tolist()函数把np.ndarray()转为list,示例代码如下: # -*- co...

python yield关键词案例测试

测试环境 win10 python 3.5 yield功能简介 简单来说,yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,P...

python 获取微信好友列表的方法(微信web)

如下所示: import urllib import urllib2 import os import time import re import cookielib im...

Django项目使用ckeditor详解(不使用admin)

Django项目使用ckeditor详解(不使用admin)

效果图: 1.安装django-ckeditor pip install django-ckeditor 如果需要上传图片或者文件,还需要安装pillow pip insta...

Python探索之创建二叉树

问题 创建一个二叉树 二叉树有限多个节点的集合,这个集合可能是: 空集 由一个根节点,和两棵互不相交的,分别称作左子树和右子树的二叉树组成 创建二叉树,创建节点,再创建节点之间...