python输出文件总行数_如何使用python计算文本文件中的总行数

这个链接(How to get line count cheaply in Python?)有很多潜在的解决方案,但它们都忽略了一种使运行速度大大加快的方法,即使用无缓冲(raw)接口、使用bytearray和执行自己的缓冲。

使用一个经过修改的计时工具,我相信下面的代码比提供的任何解决方案都要快(稍微更像是pythonic):def _make_gen(reader):

b = reader(1024 * 1024)

while b:

yield b

b = reader(1024*1024)

def rawpycount(filename):

f = open(filename, 'rb')

f_gen = _make_gen(f.raw.read)

return sum( buf.count(b'\n') for buf in f_gen )

以下是我的时间安排:rawpycount 0.0048 0.0046 1.00

bufcount 0.0074 0.0066 1.43

wccount 0.01 0.01 2.17

itercount 0.014 0.014 3.04

opcount 0.021 0.02 4.43

kylecount 0.023 0.021 4.58

simplecount 0.022 0.022 4.81

mapcount 0.038 0.032 6.82

我会贴在那里,但我是一个相对新的用户堆栈交换,没有必要的甘露。

编辑:

这完全可以使用itertools的生成器表达式来完成,但是看起来很奇怪:from itertools import (takewhile,repeat)

def rawbigcount(filename):

f = open(filename, 'rb')

bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))

return sum( buf.count(b'\n') for buf in bufgen if buf )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值