Python,针对指定文件类型,过滤空行和注释,统计行数
参考网络上代码编辑而成,无技术含量,可自行定制:
目前亲测有效,若有待完善之处,还望指出!
强调:将此统计py脚本放置项目的根目录下执行即可。
1、遍历文件,递归遍历文件夹中的所有
def getFile(basedir):
global filelists
for parent,dirnames,filenames in os.walk(basedir):
#for dirname in dirnames:
# getFile(os.path.join(parent,dirname)) #递归
for filename in filenames:
ext = filename.split('.')[-1]
#只统计指定的文件类型,略过一些log和cache文件
if ext in whitelist:
filelists.append(os.path.join(parent,filename))
2、指定文件类型:项目的代码行数,故只考虑.py文件,当然也可在指定的文件类型列表whitelist中添加其他类型
# 指定想要统计的文件类型
whitelist = ['py']
3、过滤空行和注释,注意采用的读取文件模式为‘rb’
def countLine(fname):
count = 0
single_quotes_flag = False
double_quotes_flag = False
with open(fname, 'rb') as f:
for file_line in f:
file_line = file_line.strip()
# print(file_line)
# 空行
if file_line == b'':
pass # 注释 # 开头
elif file_line.startswith(b'#'):
pass # 注释 单引号 ''' 开头
elif file_line.startswith(b"'''") and not single_quotes_flag:
single_quotes_flag = True
# 注释 中间 和 ''' 结尾
elif single_quotes_flag == True:
if file_line.endswith(b"'''"):
single_quotes_flag = False # 注释 双引号 """ 开头
elif file_line.startswith(b'"""') and not double_quotes_flag:
double_quotes_flag = True
# 注释 中间 和 """ 结尾
elif double_quotes_flag == True:
if (file_line.endswith(b'"""')):
double_quotes_flag = False # 代码
else:
count += 1
print(fname + '----', count)
# 单个文件行数
# print(fname,'----count:',count)
return count
完整源码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/05/10 21:50
# @Author : MJay_Lee
# @File : python统计行数.py
# @Contact : limengjiejj@hotmail.com import os
import time
basedir = os.path.dirname(__file__)
filelists = []
# 指定想要统计的文件类型
whitelist = ['py']
#遍历文件, 递归遍历文件夹中的所有
def getFile(basedir):
global filelists
for parent,dirnames,filenames in os.walk(basedir):
#for dirname in dirnames:
# getFile(os.path.join(parent,dirname)) #递归
for filename in filenames:
ext = filename.split('.')[-1]
#只统计指定的文件类型,略过一些log和cache文件
if ext in whitelist:
filelists.append(os.path.join(parent,filename))
#统计一个文件的行数
def countLine(fname):
count = 0
single_quotes_flag = False
double_quotes_flag = False
with open(fname, 'rb') as f:
for file_line in f:
file_line = file_line.strip()
# print(file_line)
# 空行
if file_line == b'':
pass # 注释 # 开头
elif file_line.startswith(b'#'):
pass # 注释 单引号 ''' 开头
elif file_line.startswith(b"'''") and not single_quotes_flag:
single_quotes_flag = True
# 注释 中间 和 ''' 结尾
elif single_quotes_flag == True:
if file_line.endswith(b"'''"):
single_quotes_flag = False # 注释 双引号 """ 开头
elif file_line.startswith(b'"""') and not double_quotes_flag:
double_quotes_flag = True
# 注释 中间 和 """ 结尾
elif double_quotes_flag == True:
if (file_line.endswith(b'"""')):
double_quotes_flag = False # 代码
else:
count += 1
print(fname + '----', count)
# 单个文件行数
# print(fname,'----count:',count)
return count if __name__ == '__main__' :
startTime = time.clock()
getFile(basedir)
totalline = 0
for filelist in filelists:
totalline = totalline + countLine(filelist)
print('\033[43m total lines: \033[0m'.center(20,'-'),totalline)
print('Done! Cost Time: %0.5f second' % (time.clock() - startTime))
测试对象样本,test.py:
#
'''
123
aa 哈哈
'''
"""
123
aa 哈哈 """
code1
code2
结果为:2
Python,针对指定文件类型,过滤空行和注释,统计行数的更多相关文章
- python 读取指定文件夹中的指定文件类型的文件名
import numpy as np import os path = 'F:\\wenjian'#指定文件所在路径 filetype ='.csv'#指定文件类型 def get_filename( ...
- HTML input="file" 浏览时只显示指定文件类型 xls、xlsx、csv
html input="file" 浏览时只显示指定文件类型 xls.xlsx.csv <input id="fileSelect" type=" ...
- <input type="file" />浏览时只显示指定文件类型
<input type="file" />浏览时只显示指定文件类型 <input type="file" accept="appli ...
- findstr 只搜寻指定文件类型
Title:findstr 只搜寻指定文件类型 --2012-05-04 09:27 findstr /i /m /S /C:"关键字" *.php *.asp *.jsp
- C# 获得目录下所有文件或指定文件类型文件(包含所有子文件夹)
public partial class FileGet { /// <summary> /// 私有变量 /// </summary> private static List ...
- Apache 日志设置不记录指定文件类型的方法和日志轮
Apache日志精准的记录了Web访问的记录,但对于访问量很大的站来说,日志文件过大对于分析和保存很不方便.可以在http.conf(或虚拟主机设置文件httpd-vhosts.conf)中进行设置, ...
- nginx不记录指定文件类型的日志
1.指定记录文件日志记录的内容. vim /usr/local/nginx/conf/nginx.conf如下部分: log_format dd '$remote_addr $http_x_forwa ...
- nginx不记录指定文件类型日志
1.指定记录文件日志记录的内容. vim /usr/local/nginx/conf/nginx.conf如下部分: log_format dd '$remote_addr $http_x_forwa ...
- python 将指定文件夹中的指定文件放入指定文件夹中
import os import shutil import re #获取指定文件中文件名 def get_filename(filetype): name =[] final_name_list = ...
随机推荐
- 未来HTML6出现的10个特性
网络技术正趋向于发展为一个巨大的移动APP市场,在Web开发的革命浪潮中起着指示性作用,自HTML引入以来,创建可转换,有新意的网络移动应用程序变得So easy,web开发中运用先进技术也很容易处理 ...
- 跟我一起用python画你所想吧!
0.库的引入 要想画图,我们先倒入两个库. import numpy as np import matplotlib.pyplot as plt 注:以下代码全都基于导入这两个库的前提下编写的. 1. ...
- HDU 2121——Ice_cream’s world II——————【最小树形图、不定根】
Ice_cream’s world II Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64 ...
- C#之Clone
因为类的实例是引用类型,要想用原有的类中的实例的数据的话,既要想创建原对象的一个副本的话,只能用clone方法. Clone方法分为深clone和浅clone 在C#中提供了浅clone的方法,即为M ...
- 【干货】Html与CSS入门学习笔记9-11
九.盒模型 与元素亲密接触 1.盒模型 css将每个元素都看做一个盒子,包括以下属性: 内容区content area:包含内容,内容可以决定大小,也可以自行设定宽度和高度.元素的width属性指定的 ...
- 《Cron表达式详解》
Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式: Seconds Minutes Hours DayofMonth Month ...
- MyEclipse快捷键大全,很实用
Eclipse本身很快的,但是加上了myeclipse后,就狂占内存,而且速度狂慢,那如何让Eclipse拖着myeclipse狂飚呢?这里提供一个: 技巧:取消自动validation valid ...
- 如何使用Nunit进行测试
如何使用Nunit进行测试(Visual Studio 2017 comminity) 原文:如何使用Nunit进行测试(Visual Studio 2017 comminity) 一.环境 操作系统 ...
- Centos 6/RHEL disable the IPv6 module.
http://minimallinux.blogspot.com/2013/07/centos-6rhel-disable-ipv6-module.html IPv6 was introduced t ...
- java:图片压缩
java使用google开源工具实现图片压缩 :http://www.cnblogs.com/linkstar/p/7412012.html