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


当前回答

你所需要做的就是使用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)

这也会自动关闭文件。

其他回答

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()

我不敢相信这能像@john-la-rooy的回答看起来那么简单。因此,我使用逐行读写重新创建了cp命令。这是疯狂的快。

#!/usr/bin/env python3.6

import sys

with open(sys.argv[2], 'w') as outfile:
    with open(sys.argv[1]) as infile:
        for line in infile:
            outfile.write(line)

老派方法:

fh = open(file_name, 'rt')
line = fh.readline()
while line:
    # do stuff with line
    line = fh.readline()
fh.close()

如果你在文件中没有换行符,你可以这样做:

with open('large_text.txt') as f:
  while True:
    c = f.read(1024)
    if not c:
      break
    print(c,end='')

请试试这个:

with open('filename','r',buffering=100000) as f:
    for line in f:
        print line