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 = ...
随机推荐
- CTeX里面CTRL-Space和中文输入法的冲突问题解决
我使用的是windows xp,相信下面的方法也能应用到win7等windows系统上. 我希望在CTex套件的WinEdt 6.0里使用模板自动插入内容时,想快速从上到下遍历” * “并修改. 通过 ...
- (转) IP子网划分
原文:http://blog.csdn.net/birdie_l/article/details/77994610 子网划分公式计算法 实例一 实例二 心算思路总结: B类公式算法举例: 总结:此表 ...
- Java学习笔记--继承和多态(下)
1.通过继承来开发超类(superclass) 2.使用super 关键词唤起超类的构造方法 3.在超类中覆盖方法 4.区分override和overload 5.在Object类中探索toStrin ...
- 修改model,映射到表中
1. 当使用EF code first创建数据表后,数据库中会自动创建一个名为:dbo.__MigrationHistory的系统数据表, 如果尚未启用数据库迁移功能,那么每次在应用程序运行时,都会对 ...
- vue学习第二天 ------ 临时笔记
学习链接: vue.js官方文档: https://cn.vuejs.org/v2/guide/index.html vue.js API: https://cn.vuejs.org/v2/api/# ...
- mint-ui popup自动关闭
<template> <div class="hello"> <input type="text" v-model="n ...
- javascript中如何实现继承
javascript中如何实现继承 // 原型方式的'继承' function Person(name) { //定义一个Person的构造函数 this.name = name; //添加属性 } ...
- (转)两张Firefox OS 系统截图
锁屏图 锁屏就是一个向上的小火箭. 桌面 桌面又是另一种风格. 注意 以上为Android系统下运行b2g. 原文地址,TZone
- IplImage转为Mat的方法
IplImage* S_change_out; Mat matimg; matimg=cvarrToMat(S_change_out);
- 笨办法学Python(二十)
习题 20: 函数和文件 回忆一下函数的要点,然后一边做这节练习,一边注意一下函数和文件是如何在一起协作发挥作用的. from sys import argv script, input_file = ...