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 = ...
随机推荐
- (转)Memcached用法--参数和命令详解
Memcached用法--参数和命令详解 1. memcached 参数说明: # memcached -h 1.1 memcached 的参数 常用参数 -p <num> 监听的TCP端 ...
- http三次握手四次挥手
最近一直忙于看前端vue相关内容,后端相关内容没有跟进,文章停了3周,,,哎,还是懒吧!子曰生命在于运动,该学习还是要学的,文章嘛也还是要整理滴,不扯了--- 参考: https://blog.csd ...
- Linux证书登录,禁用密码
如果验证成功的话就可以关闭密码登陆方式了, 编辑/etc/ssh/sshd_config, 将PasswordAuthentication改为no, ChallengeResponseAuthenti ...
- 小程序 页面到详情的id传递
比如电影列表页跳转到电影详情页 在movie.js获取movieId; processDoubanData: function (moviesDouban, settedKey, categoryTi ...
- 斗鱼扩展--notifications提示(十二)
来说下 桌面通知 Notification,HTML5支持 Web Notifications 的实例,但是要经过用户允许, chrome://settings/content/notificati ...
- BZOJ4653: [Noi2016]区间(线段树 双指针)
题意 题目链接 Sol 按照dls的说法,一般这一类的题有两种思路,一种是枚举一个点\(M\),然后check它能否成为答案.但是对于此题来说好像不好搞 另一种思路是枚举最小的区间长度是多少,这样我们 ...
- Form上传编译
编译上传的Form,使用命令: 在R12服务器上: cd $AU_TOP/forms/US frmcmp_batch module=$CUX_TOP/forms/ZHS/XXX.fmbuserid=a ...
- [Maven]Eclipse集成遇到的问题
当maven项目导入到eclipse中后使用eclipse提供的maven命令执行任意一个出现 Exception in thread "main" java.lang.Unsup ...
- 485和OPT
也许很多人都以为嫁给美国公民最快要绿卡,其实还有一个更快的婚姻绿卡方式:嫁给485男/女.这是什么意思呢? 嫁给美国公民,配偶方最快会在4-5个月内获得条件绿卡,两年后才能获得永久绿卡.在这两年内,如 ...
- myeclipse 10 创建webservice
java 快捷创建webservice 收集一下,方便一下查阅 详情去看一下这个老哥,里面写得非常详细: http://hyan.iteye.com/ -- http://www.cnblogs.co ...