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

yipeiwu_com6年前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设计】。

相关文章

Python实现完整的事务操作示例

本文实例讲述了Python事务操作实现方法。分享给大家供大家参考,具体如下: #coding=utf-8 import sys import MySQLdb class Transf...

Django项目中使用JWT的实现代码

Django项目中使用JWT的实现代码

1.requiremwnts: Django版本:2.2 python版本:3.6 djangorestframework版本:3.1 djangorestframew...

Python tkinter label 更新方法

Python tkinter label 更新方法

网上看的两个例子关于tkinter界面更新的,简单易懂,分享一下。 例子_1: 代码_1: from tkinter import Tk, Checkbutton, Label f...

Python基于百度云文字识别API

本文实例为大家分享了Python实现最简单的文字识别的具体代码,供大家参考,具体内容如下 Python版本:3.6.5 百度云提供的文字识别技术,准确率还是非常高的,而且每天还有5w次免...

python通过cookie模拟已登录状态的初步研究

python通过cookie模拟已登录状态的初步研究

对于那些需要在登录环境下进行的爬虫操作,模拟登陆或伪装已登录状态是一个刚需。 分析了网上关于模拟登录的例子,很多都基于用户名/密码发起一个post请求,遇到有图片验证码的,比较理想的方法...