用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设计】。

相关文章

pyqt5 禁止窗口最大化和禁止窗口拉伸的方法

如下所示: 在def __init__(self):函数里添加 self.setFixedSize(self.width(), self.height()) 以上这篇pyqt5 禁止窗口...

pymysql模块的操作实例

pymysql 模块! pymysql模块时一个第三方模块!需要下载: pymysql的基本使用: import pymysql conn = pymysql.connect(...

如何将你的应用迁移到Python3的三个步骤

Python 2.x 很快就要 失去官方支持 了,尽管如此,从 Python 2 迁移到 Python 3 却并没有想象中那么难。我在上周用了一个晚上的时间将一个 3D 渲染器的前端代码...

对python 中re.sub,replace(),strip()的区别详解

对python 中re.sub,replace(),strip()的区别详解

1.strip(): str.strip([chars]);去除字符串前面和后面的所有设置的字符串,默认为空格 chars -- 移除字符串头尾指定的字符序列。 st = " he...

windows下ipython的安装与使用详解

windows下ipython的安装与使用详解

ipython的安装 ipython可以直接使用pip install ipython安装 ,如果安装失败按如下步骤手动进行安装 所需文件下载:    ...