我想逐行读取一个大文件(>5GB),而不将其全部内容加载到内存中。我不能使用readlines(),因为它在内存中创建了一个非常大的列表。


当前回答

blaze项目在过去6年里取得了长足的进展。它有一个简单的API,涵盖了pandas功能的一个有用子集。

dask。Dataframe内部负责分块,支持许多可并行操作,并允许您轻松地将切片导出回pandas,以便在内存中操作。

import dask.dataframe as dd

df = dd.read_csv('filename.csv')
df.head(10)  # return first 10 rows
df.tail(10)  # return last 10 rows

# iterate rows
for idx, row in df.iterrows():
    ...

# group by my_field and return mean
df.groupby(df.my_field).value.mean().compute()

# slice by column
df[df.my_field=='XYZ'].compute()

其他回答

在文件对象上使用for循环逐行读取。使用open(…)让上下文管理器确保文件读取后关闭:

with open("log.txt") as infile:
    for line in infile:
        print(line)

blaze项目在过去6年里取得了长足的进展。它有一个简单的API,涵盖了pandas功能的一个有用子集。

dask。Dataframe内部负责分块,支持许多可并行操作,并允许您轻松地将切片导出回pandas,以便在内存中操作。

import dask.dataframe as dd

df = dd.read_csv('filename.csv')
df.head(10)  # return first 10 rows
df.tail(10)  # return last 10 rows

# iterate rows
for idx, row in df.iterrows():
    ...

# group by my_field and return mean
df.groupby(df.my_field).value.mean().compute()

# slice by column
df[df.my_field=='XYZ'].compute()

你所需要做的就是使用file对象作为迭代器。

for line in open("log.txt"):
    do_something_with(line)

在最近的Python版本中使用上下文管理器更好。

with open("log.txt") as fileobject:
    for line in fileobject:
        do_something_with(line)

这也会自动关闭文件。

最好使用迭代器。 相关:fileinput -迭代多个输入流中的行。

从文档中可以看出:

import fileinput
for line in fileinput.input("filename", encoding="utf-8"):
    process(line)

这将避免将整个文件一次复制到内存中。

这是我找到的最佳解决方案,我在330 MB的文件上尝试了一下。

lineno = 500
line_length = 8
with open('catfour.txt', 'r') as file:
    file.seek(lineno * (line_length + 2))
    print(file.readline(), end='')

其中line_length是单行中的字符数。例如,“abcd”的行长为4。

我添加了2个行长来跳过'\n'字符并移动到下一个字符。