python获取大文件行数

python获取大文件行数

背景:处理一些日志或者请求数据时,几百万行的数据,有时候在做性能测试任务时估算出大概需要的词表数,需要一定行数的数据,需要提前看下原始文件大小,在这记一下,的确比较快

代码如下:

# 获取文件行数,一块一块读取
def get_file_lines(filePath):
    with open(filePath, 'rb') as f:
        count = 0
        buf_size = 1024 * 1024
        buf = f.read(buf_size)
        while buf:
            count += buf.count(b'\n')
            buf = f.read(buf_size)
        return count
		
# 用法
filePath = "/home/alisleepy/all_query"
lines = get_file_lines(filePath)
print "文件行数:" + str(lines)

本文来自博客园,作者:alisleepy,转载请注明原文链接:https://www.cnblogs.com/alisleepy/p/15534601.html

原文地址:https://www.cnblogs.com/alisleepy/p/15534601.html