Python如何读取大文件 Python读取大文件代码实例

作者:袖梨 2019-12-18

本篇文章小编给大家分享一下Python读取大文件代码实例,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

通常对于大文件读取及处理,不可能直接加载到内存中,因此进行分批次小量读取及处理

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)

完成

相关文章

精彩推荐