前言:通常對於大文件讀取及處理,不可能直接加載到內存中,因此進行分批次小量讀取及處理
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)