Python逐块读取大文件行数的代码

Python逐块读取大文件行数的代码 - 为程序员服务

python数文件行数最简单的方法是使用enumerate方法,但是如果文件很大的话,这个方法就有点慢了,我们可以逐块的读取文件的内容,然后按块来数块内的 数,从而确定行数。

如下实现代码:

def blocks(file, size=65536):
    while True:
        b = files.read(size)
        if not b: break
        yield b

with open("file", "r") as f:
    print sum(bl.count("
") for bl in blocks(f))
原文地址:https://www.cnblogs.com/lexus/p/3325489.html