python计算文件行数的三种方法

import timeit,os

def linecount_1():
    return len(open('data.sql').readlines())#最直接的方法

def linecount_2():
    count = -1 #让空文件的行号显示0
    for count,line in enumerate(open('data.sql')): pass 
    #enumerate格式化成了元组,count就是行号,因为从0开始要+1
    return count+1

def linecount_3():
    count = 0
    thefile = open('data.sql','rb')
    while 1:
        buffer = thefile.read(65536)
        if not buffer:break
        count += buffer.count('\n')#通过读取换行符计算
    return count

for f in linecount_1,linecount_2,linecount_3:
    print f.__name__,f()

for f in linecount_1,linecount_2,linecount_3:
    t = timeit.Timer(f,'')#第一个参数是函数,第二个参数是环境,例如import模块
    print min(t.repeat(100,3))#第一个参数是重复整个测试的次数,第二个参数是每个测试中调用被计时语句的次数。


转载于:https://my.oschina.net/taisha/blog/55877

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值