gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:16:01 32 4
gpt4 key购买 nike

我有一个大文本文件 (~7 GB)。我正在寻找是否存在读取大文本文件的最快方法。我一直在阅读有关使用多种方法逐 block 读取以加快进程的信息。

例如 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**

为了每秒处理 96,900 行文本。其他 authors建议使用 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)) 将返回文件 f 的下 n 行的列表。在循环中使用它会给你提供 n

block 的文件

最佳答案

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

每次将一行读入内存,完成后关闭文件...

关于Python 读取大型文本文件(几 GB)的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14944183/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com