首页 > 技术文章 > Python读取大文件

gambler 2019-12-17 23:14 原文

前言:通常对于大文件读取及处理,不可能直接加载到内存中,因此进行分批次小量读取及处理
I、第一种读取方式
一行一行的读取,速度较慢
def read_line(path):
    with open(path, 'r', encoding='utf-8') as fout:
        line = fout.readline()
        while line:
            line = fout.readline()
            print(line)
II、第二种读取方式
设置每次读取大小,从而完成多行快速读取
def read_size(path):
    with open(path, "r", encoding='utf-8') as fout:
        while 1:
            buffer = fout.read(8 * 1024 * 1024)
            if not buffer:
                break
            print(buffer)
III、第三种读取方式
使用itertools模块,islice返回的是一个生成器,可以用list格式化
from itertools import islice
def read_itertools(path):
    with open(path, 'r', encoding='utf-8') as fout:
        list_gen = islice(fout, 0, 5)  # 两个参数分别表示开始行和结束行
        for line in list_gen:
            print(line)
完成




推荐阅读