首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python读取大型文本文件的最快方法(几GB)

Python读取大型文本文件的最快方法(几GB)
EN

Stack Overflow用户
提问于 2013-02-19 03:50:35
回答 1查看 97K关注 0票数 37

我有一个很大的文本文件(~7 GB)。我正在寻找是否存在读取大型文本文件的最快方法。我一直在读一些关于使用几种方法来逐块读取以加快进程的文章。

在示例中effbot建议

代码语言:javascript
复制
# 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**

以便每秒处理96,900行文本。其他authors建议使用islice()

代码语言:javascript
复制
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))将返回文件f的后续n行的列表。在循环中使用它将以n行的形式给出文件

EN

回答 1

Stack Overflow用户

发布于 2013-02-19 03:57:02

代码语言:javascript
复制
with open(<FILE>) as FileObj:
    for lines in FileObj:
        print lines # or do some other thing with the line...

将一次读取一行到内存,并在完成时关闭文件...

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14944183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档