-->

Python来读取大文本文件(几个GB)[复制]最快的方法(Python fastest way t

2019-07-20 03:16发布

这个问题已经在这里有一个答案:

  • 如何读取大文件,一行行,在Python 10个回答

我有一个大的文本文件(〜7 GB)。 我期待是否存在读取大的文本文件的最快方式。 我一直在阅读有关使用几种方法为,以加快这一进程读取块逐块。

在例如effbot建议

# File: readline-example-3.py

file = open("sample.txt")

while 1:
    lines = file.readlines(100000)
    if not lines:
        break
    for line in lines:
        pass # do something**strong text**

为了处理96900行每秒文字。 其他作者建议使用islice()

from itertools import islice

with open(...) as f:
    while True:
        next_n_lines = list(islice(f, n))
        if not next_n_lines:
            break
        # process next_n_lines

list(islice(f, n))将返回下一个列表n文件的行f 。 使用这个循环里面会给你的大块文件n线

Answer 1:

with open(<FILE>) as FileObj:
    for lines in FileObj:
        print lines # or do some other thing with the line...

将读取的时间内存一条线,并在完成后关闭文件...



文章来源: Python fastest way to read a large text file (several GB) [duplicate]